<template>
  <div v-loading="allLoading" class="order-create-form-wrapper">
    <div class="order-create-form-container">
      <div class="header">
        <h4 class="title">新建工单</h4>
        <div class="btn_group">
          <h-plain-button @click="submitOrder">提交</h-plain-button>
          <h-button @click="onCancelOrder">取消</h-button>
        </div>
      </div>

      <div class="divider"></div>

      <div class="form-container">
        <!-- 客户信息 -->
        <div ref="customerInfoDiv" class="customer">
          <div class="title">客户信息</div>
          <el-form
            ref="customerInfoFormInstance"
            :model="basicData"
            :rules="rules"
            label-position="top"
            inline-message
          >
            <div class="form-box">
              <!-- 商用：客户，家用：店铺/渠道 -->
              <el-form-item
                :label="
                  basicData.departmentId === departmentFixedData.business ? '客户' : '店铺/渠道'
                "
                prop="name"
                class="top"
              >
                <el-popover :visible="customerSelectPopoverVisible" :width="370">
                  <template #reference>
                    <el-input
                      v-model.trim="basicData.name"
                      :placeholder="`请输入${
                        basicData.departmentId === departmentFixedData.business
                          ? '客户'
                          : '店铺/渠道'
                      }`"
                      clearable
                      :disabled="isDisabledUserInput"
                      @clear="onClearUserInfo"
                      @input="handleCustomerNameInput"
                      @blur="customerSelectPopoverVisible = false"
                    />
                  </template>

                  <el-table
                    v-loading="getUserOptionListLoading"
                    :data="userOptionList"
                    :border="true"
                    :max-height="300"
                    @row-click="(user: UserMainContactPersonOption) => handleChangeUser(user, 1)"
                  >
                    <!-- 序号 -->
                    <el-table-column type="index" label="序号" width="50" :align="'center'" />

                    <!-- 客户名称 -->
                    <el-table-column
                      show-overflow-tooltip
                      label="客户名称"
                      prop="name"
                      min-width="120"
                    />

                    <!-- 客户手机号 -->
                    <el-table-column label="客户手机号" prop="phone" width="120" />
                  </el-table>
                </el-popover>
              </el-form-item>

              <!-- 业务手机号 -->
              <el-form-item
                v-if="basicData.departmentId === departmentFixedData.business"
                label="业务手机号"
              >
                <el-input
                  v-model.trim="basicData.businessPhone"
                  maxlength="11"
                  placeholder="请输入业务手机号"
                  @input="handleBusinessPhoneInput"
                />
              </el-form-item>

              <!-- 店铺联系方式 -->
              <el-form-item v-else label="店铺联系方式">
                <el-input
                  v-model.trim="basicData.businessPhone"
                  maxlength="11"
                  placeholder="请输入店铺联系方式"
                  @input="handleBusinessPhoneInput"
                />
              </el-form-item>

              <!-- 商用：反馈人，家用：联系人 -->
              <el-form-item
                :label="
                  basicData.departmentId === departmentFixedData.business ? '反馈人' : '联系人'
                "
                prop="repairCompany"
              >
                <el-popover :visible="feedbackPersonSelectPopoverVisible" :width="370">
                  <template #reference>
                    <el-input
                      v-model.trim="basicData.repairCompany"
                      :placeholder="`请输入${
                        basicData.departmentId === departmentFixedData.business
                          ? '反馈人'
                          : '联系人'
                      }`"
                      clearable
                      @clear="onClearUserInfo2"
                      @input="handleFeedbackPersonInput"
                      @blur="feedbackPersonSelectPopoverVisible = false"
                    />
                  </template>

                  <el-table
                    v-loading="getSendRepairUserOptionListLoading"
                    :data="sendRepairUserOptionList"
                    :border="true"
                    :max-height="300"
                    @row-click="(user: UserMainContactPersonOption) => handleChangeUser(user, 2)"
                  >
                    <!-- 序号 -->
                    <el-table-column type="index" label="序号" width="50" :align="'center'" />

                    <!-- 客户名称 -->
                    <el-table-column
                      show-overflow-tooltip
                      label="客户名称"
                      prop="name"
                      min-width="120"
                    />

                    <!-- 客户手机号 -->
                    <el-table-column label="客户手机号" prop="phone" width="120" />
                  </el-table>
                </el-popover>
              </el-form-item>

              <!-- 商用：反馈电话，家用：联系方式 -->
              <el-form-item
                :label="
                  basicData.departmentId === departmentFixedData.business ? '反馈电话' : '联系方式'
                "
                prop="repairCompanyPhone"
              >
                <el-input
                  v-model.trim="basicData.repairCompanyPhone"
                  maxlength="11"
                  :placeholder="`请输入${
                    basicData.departmentId === departmentFixedData.business
                      ? '反馈电话'
                      : '联系方式'
                  }`"
                  @input="handleFeedbackPhoneInput"
                />
              </el-form-item>

              <!-- 店名 -->
              <el-form-item
                v-if="basicData.departmentId === departmentFixedData.business"
                label="店名"
                prop="storeName"
              >
                <el-input v-model="basicData.storeName" placeholder="请输入店名" />
              </el-form-item>

              <!-- 所在地区 -->
              <el-form-item label="所在地区" prop="customerAddress">
                <template #label>
                  <div>
                    <span style="color: #f56767">*</span>
                    <span>所在地区</span>
                  </div>
                </template>
                <SingleAddress ref="singleAddressRef" :address="addrs" />
              </el-form-item>

              <!-- 详细地址 -->
              <el-form-item label="详细地址" prop="address">
                <el-input
                  v-model.trim="basicData.address"
                  maxlength="200"
                  placeholder="请输入详细地址"
                  show-word-limit
                  type="textarea"
                  resize="both"
                  class="detail_address"
                />
              </el-form-item>

              <!--地址识别-->
              <el-form-item label="地址识别">
                <div class="address_identify">
                  <el-input
                    v-model.trim="allUserInfo"
                    maxlength="300"
                    show-word-limit
                    placeholder="粘贴整段信息到此文本框如：张三，15815151515，北京市市辖区石景山区中山路25号"
                    type="textarea"
                    resize="both"
                  />
                  <HButton type="primary" :loading="addrParseLoading" @click="onAddrParse">
                    识别
                  </HButton>
                </div>
              </el-form-item>

              <!--公司地址、详细地址-->
              <!-- <div class="form_item_container"> -->
              <!-- 送修人 -->
              <!-- <el-form-item class="customer_send top" label="送修人" prop="sendForRepairUsername">
                  <el-input
                    v-model.trim="basicData.sendForRepairUsername"
                    placeholder="请输入送修人"
                  />
                </el-form-item> -->

              <!-- 送修电话 -->
              <!-- <el-form-item class="customer_send" label="送修电话" prop="sendForRepairPhone">
                  <el-input
                    v-model.trim="basicData.sendForRepairPhone"
                    maxlength="11"
                    placeholder="请输入送修电话"
                    @input="
                      basicData.sendForRepairPhone = basicData.sendForRepairPhone.replace(
                        /[^0-9]/g,
                        '',
                      )
                    "
                  />
                </el-form-item>
              </div> -->
            </div>
          </el-form>
        </div>

        <!-- 工单信息 -->
        <div ref="basicInfoDiv" class="order">
          <div class="title">工单信息</div>
          <el-form
            ref="basicInfoFormInstance"
            :model="basicData"
            :rules="rules"
            label-position="top"
            inline-message
          >
            <!-- 报单时间 -->
            <el-form-item label="报单时间">
              <el-date-picker
                v-model="now"
                :default-value="new Date()"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm"
              />
            </el-form-item>

            <!-- 产品类型 -->
            <el-form-item label="产品类型" prop="departmentId">
              <el-select
                v-model="basicData.departmentId"
                placeholer="请选择产品类型"
                @change="changeWorkGoodsType"
              >
                <el-option
                  v-for="(option, optionIndex) in departmentOptions"
                  :key="optionIndex"
                  :label="option.name"
                  :value="option.id"
                />
              </el-select>
            </el-form-item>

            <!-- 销售渠道 -->
            <el-form-item
              v-if="basicData.departmentId === departmentFixedData.family"
              label="销售渠道"
            >
              <el-select v-model="basicData.saleChannel" placeholder="请选择销售渠道" clearable>
                <el-option
                  v-for="item in saleChannelOptionList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
                <template v-if="basicData.departmentId === departmentFixedData.family">
                  <el-option
                    v-for="item in saleChannelOptionList2"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </template>
              </el-select>
            </el-form-item>

            <!-- 工单类型 -->
            <el-form-item label="工单类型" prop="moduleId">
              <el-select
                v-model="basicData.moduleId"
                :loading="loading"
                :filter-method="handleGetOrderTypeOptions"
                clearable
                filterable
                placeholder="工单类型"
                remote-show-suffix
                @clear="type = ''"
              >
                <el-option
                  v-for="(item, index) in modules"
                  :key="index"
                  :disabled="item.disabled"
                  :label="item.name"
                  :value="item.id"
                  @click="handleChangeModule(item)"
                />
              </el-select>
            </el-form-item>

            <!-- 购买平台订单号 -->
            <el-form-item
              v-if="basicData.departmentId === departmentFixedData.family"
              label="购买平台订单号"
              prop="buyPlatformOrderNo"
            >
              <el-input v-model="basicData.buyPlatformOrderNo" placeholder="请输入购买平台订单号" />
            </el-form-item>

            <!-- 服务类型 -->
            <el-form-item
              v-if="departmentFixedData.business === basicData.departmentId"
              label="服务类型"
              :prop="departmentFixedData.business === basicData.departmentId ? 'serviceType' : ''"
            >
              <el-select v-model="basicData.serviceType" placeholder="请选择服务类型">
                <template v-if="basicData.departmentId === departmentFixedData.family">
                  <el-option
                    v-for="item in serviceTypeOptionList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </template>

                <template v-else>
                  <el-option
                    v-for="item in serviceTypeOptionList2"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </template>
              </el-select>
            </el-form-item>

            <!-- 服务方式 -->
            <el-form-item
              v-if="departmentFixedData.business === basicData.departmentId"
              label="服务方式"
              :prop="departmentFixedData.business === basicData.departmentId ? 'serviceMode' : ''"
            >
              <el-select v-model="basicData.serviceMode" placeholer="请选择服务方式">
                <el-option
                  v-for="item in serviceModeOptionList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <!-- 预约时间 -->
            <el-form-item label="预约时间">
              <div class="appointment-time">
                <el-date-picker
                  v-model="basicData.orderReservationDate"
                  placeholder="请选择日期"
                  :disabled-date="(time: Date) => time.getTime() < Date.now() - 8.64e7"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  @clear="onClearAppointmentTime"
                />
                <el-time-select
                  v-model="basicData.orderReservationstartTime"
                  start="05:00"
                  step="02:00"
                  end="23:00"
                  placeholder="开始时间"
                  :max-time="basicData.orderReservationEndTime"
                  @clear="onClearAppointmentTime"
                />
                <el-time-select
                  v-model="basicData.orderReservationEndTime"
                  start="05:00"
                  step="02:00"
                  end="23:00"
                  placeholder="结束时间"
                  :min-time="basicData.orderReservationstartTime"
                  @clear="onClearAppointmentTime"
                />
              </div>
            </el-form-item>

            <!-- 故障描述 -->
            <el-form-item label="故障描述" prop="content">
              <div class="fault-desc-container">
                <el-input
                  v-model.trim="basicData.content"
                  maxlength="200"
                  placeholder="请输入故障描述"
                  show-word-limit
                  type="textarea"
                  resize="both"
                  :class="'desc-28-height'"
                />
              </div>
            </el-form-item>

            <!-- 故障类型(反馈故障) -->
            <el-form-item
              v-if="departmentFixedData.business === basicData.departmentId"
              label="故障类型(反馈故障)"
              :prop="
                departmentFixedData.business === basicData.departmentId
                  ? 'faultTypeRelationVos'
                  : ''
              "
            >
              <el-select
                :model-value="
                  basicData.faultTypeRelationVos.map((item) => item.oneFaultTypeId)?.[0]
                "
                :loading="getFaultTypeOptionsLoading"
                placeholder="请选择故障类型(反馈故障)"
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="2"
                filterable
                :filter-method="handleFaultTypeOptionsSearch"
                @change="handleFaultTypeSelect"
                @remove-tag="handleRemoveFaultType"
              >
                <el-option
                  v-for="(faultType, faultTypeIndex) in faultTypeOptions"
                  :key="faultTypeIndex"
                  :value="faultType.id"
                  :label="faultType.name"
                />
              </el-select>
            </el-form-item>

            <!-- 受理客服 -->
            <el-form-item label="受理客服">
              <el-select
                v-model="basicData.empId"
                :loading="loading"
                :filter-method="getCustomerOptions"
                clearable
                filterable
                placeholder="受理客服"
                remote-show-suffix
              >
                <el-option :value="0" label="按规则分配">
                  <div style="display: flex; justify-content: space-between; align-items: center">
                    <span>按规则分配</span> <span style="color: #fb9337">系统</span>
                  </div>
                </el-option>
                <el-option
                  v-for="item in customerOptions"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <!-- 客服备注 -->
            <el-form-item label="客服备注" prop="remark">
              <el-input v-model="basicData.remark" type="textarea" placeholder="请输入客服备注" />
            </el-form-item>

            <!-- 责任归属 -->
            <el-form-item
              v-if="departmentFixedData.business === basicData.departmentId"
              label="责任归属"
              :prop="
                departmentFixedData.business === basicData.departmentId ? 'accountability' : ''
              "
            >
              <el-select v-model="basicData.accountability" placeholer="请选择责任归属">
                <el-option
                  v-for="item in dutyBelongToOptionList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
                <template v-if="basicData.departmentId === departmentFixedData.family">
                  <el-option
                    v-for="item in dutyBelongToOptionList2"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </template>
              </el-select>
            </el-form-item>

            <!-- 分派网点 -->
            <el-form-item label="分派网点">
              <el-select
                v-model="network"
                :loading="loading"
                :filter-method="getNetworkPageSelectList"
                clearable
                filterable
                placeholder="分派网点"
                remote-show-suffix
                :disabled="userStore.isCurrentRoleNetwork && !!loginedAccountNetwork"
              >
                <el-option :value="0" label="按规则分配">
                  <div style="display: flex; justify-content: space-between; align-items: center">
                    <span>按规则分配</span> <span style="color: #fb9337">系统</span>
                  </div>
                </el-option>
                <el-option
                  v-for="item in networks"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <!-- 工单分类 -->
            <!-- <el-form-item label="工单分类">
              <el-cascader
                v-model="type"
                :before-filter="inputChangeType"
                :options="types"
                :props="CascaderProps"
                clearable
                filterable
                placeholder="工单分类"
                @visible-change="changeType"
              />
            </el-form-item> -->

            <!-- 受理客服 -->
            <!-- <el-form-item label="受理客服">
              <el-select
                v-model="customer"
                :loading="loading"
                :filter-method="getCustomerOptions"
                clearable
                filterable
                placeholder="受理客服"
                remote-show-suffix
              >
                <el-option :value="0" label="按规则分配">
                  <div style="display: flex; justify-content: space-between; align-items: center">
                    <span>按规则分配</span> <span style="color: #fb9337">系统</span>
                  </div>
                </el-option>
                <el-option
                  v-for="item in customerOptions"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item> -->

            <!-- 处理方式 -->
            <!-- <el-form-item label="处理方式">
              <el-cascader
                v-model="method"
                :before-filter="inputChangeMethod"
                :options="methodss"
                :props="CascaderProps"
                clearable
                filterable
                placeholder="处理方式"
                @visible-change="changeMmethod"
              />
            </el-form-item> -->

            <!-- <template v-if="type === 2"> -->

            <!-- 故障现象 -->
            <!-- <el-form-item label="故障现象" prop="faultRelationVos">
              <el-select
                :model-value="basicData.faultRelationVos.map((item) => item.faultId)"
                :loading="getFaultByTypeLoading"
                placeholder="请选择故障现象"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="2"
                allow-create
                filterable
                :no-data-text="
                  basicData.faultTypeRelationVos.map((item) => item.oneFaultTypeId).length === 0
                    ? '请选择故障现象'
                    : '无数据'
                "
                @change="handleFaultPhenomenonChange"
                @remove-tag="handleFaultPhenomenonRemove"
              >
                <el-option
                  v-for="(fault, faultIndex) in faultList"
                  :key="faultIndex"
                  :value="fault.id"
                  :label="`${fault.code} ${fault.name}`"
                  :disabled="fault.disabled"
                >
                  <div class="fault-phenomenon-option">
                    <div style="margin-right: 20px">
                      <h-tooltip-text
                        :text="fault.code"
                        :max-width="60"
                        :height="36"
                        text-align="right"
                      />
                    </div>
                    <div>
                      <h-tooltip-text :text="fault.name" :max-width="320" :height="36" />
                    </div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item> -->
            <!-- </template> -->

            <!-- <template v-if="type === 2"> -->
            <!-- 故障原因 -->
            <!-- <el-form-item label="故障原因" prop="faultReason">
              <el-select
                v-if="faultReasonOptions.length"
                :model-value="basicData.faultReason.map((item) => item.id)"
                placeholder="请选择故障原因"
                allow-create
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="3"
                filterable
                default-first-option
                :reserve-keyword="false"
                @change="handleFaultReasonSelect"
              >
                <el-option
                  v-for="(reason, reasonIndex) in faultReasonOptions"
                  :key="reasonIndex"
                  :label="reason.content"
                  :value="reason.id"
                >
                  <h-tooltip-text :text="reason.content" :max-width="150" :height="32" />
                </el-option>
              </el-select>
              <el-input
                v-else
                v-model.trim="basicData.faultReason"
                placeholder="请输入故障原因"
                show-word-limit
                type="textarea"
                resize="both"
                class="desc-28-height"
              />
            </el-form-item> -->

            <!-- 解决措施 -->
            <!-- <el-form-item label="解决措施" prop="solution">
              <el-select
                v-if="solveOptions.length"
                :model-value="basicData.solution.map((item) => item.id)"
                placeholder="请选择解决措施"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="3"
                filterable
                allow-create
                default-first-option
                :reserve-keyword="false"
                @change="handleSolveSelect"
              >
                <el-option
                  v-for="(solve, solveIndex) in solveOptions"
                  :key="solveIndex"
                  :label="solve.content"
                  :value="solve.id"
                >
                  <h-tooltip-text
                    :text="solve.content"
                    :max-width="300"
                    :height="32"
                  ></h-tooltip-text>
                </el-option>
              </el-select>
              <el-input
                v-else
                v-model.trim="basicData.solution"
                placeholder="请输入解决措施"
                show-word-limit
                type="textarea"
                resize="both"
                class="desc-28-height"
              />
            </el-form-item> -->
            <!-- </template> -->

            <!-- 服务级别 -->
            <!-- <el-form-item label="服务级别">
              <el-select
                v-model="grade"
                placeholder="服务级别"
                :loading="loading"
                :filter-method="getworkLevelPageSelect"
                clearable
                filterable
                remote-show-suffix
              >
                <el-option
                  v-for="item in grades"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item> -->

            <!-- 工单来源 -->
            <el-form-item label="工单来源" prop="workSourceId">
              <el-select v-model="basicData.workSourceId" placeholder="请选择工单来源">
                <el-option
                  v-for="(item, index) in workSourceList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <!-- 保修类型 -->
            <el-form-item label="保修类型" prop="overinsured">
              <el-select v-model="basicData.overinsured" placeholder="请选择保修类型">
                <el-option key="0" label="保内" :value="false" />
                <el-option key="1" label="保外" :value="true" />
              </el-select>
            </el-form-item>

            <!-- 故障图片 -->
            <el-form-item label="故障图片（最多只能上传3张）">
              <div class="upload_file_container">
                <div v-for="(item, index) in fileList" :key="index">
                  <h-image
                    :preview-src-list="fileList.map((file) => file.image)"
                    :src="item.image"
                    :initial-index="index"
                    :width="80"
                    :height="50"
                    :padding="2"
                    @del="handleDelOrderPicture(index)"
                  />
                  <div class="file_name">
                    <h-tooltip-text :text="item.name" :max-width="80" :height="16" />
                  </div>
                </div>
                <div v-if="fileList.length < 3">
                  <el-upload
                    v-model="fileList"
                    class="order-picture-upload"
                    :auto-upload="false"
                    :on-change="handleUploadOrderPicture"
                    :show-file-list="false"
                    accept="image/*"
                    action="#"
                    drag
                    multiple
                  >
                    <el-icon :size="24" color="#007cff">
                      <UploadFilled />
                    </el-icon>
                  </el-upload>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>

        <div ref="goodInfoDiv" class="good-info">
          <good-info
            ref="goodInfoInstance"
            :factory-id="String(network) || ''"
            :user-id="basicData.userId"
            @change-goods="onGoodInfoChangeGoodList"
            @change-user="handleGoodInfoChangeUser"
          />
        </div>

        <!-- 自定义信息 -->
        <!-- <div v-if="customFieldList.length > 0" ref="customInfoDiv" class="custom_info"> -->
        <!-- <div class="title">工单维修信息</div> -->
        <!-- <div class="form-content"> -->
        <!-- <el-form
              v-for="(field, index) in customFieldList.filter((item) =>
                [1, 3, 4, 8, 9, 10].includes(item.type),
              )"
              ref="customFieldFormInstance"
              :key="index"
              :model="customFieldList[field.formCustomFieldIndex]"
              label-position="top"
              inline-message
            > -->
        <!-- <el-form-item
                :label="field.name"
                :prop="field.type === 4 ? 'valList' : 'val'"
                :rules="[
                  {
                    required: field.required,
                    message: field.tip || '请输入内容',
                    trigger: ['change', 'blur'],
                  },
                ]"
              > -->
        <!-- 单行文本 -->
        <!-- <el-input
                  v-if="field.type === 1"
                  v-model.trim="customFieldList[field.formCustomFieldIndex].val"
                  :placeholder="field.tip || '请输入内容'"
                  maxlength="100"
                /> -->

        <!-- 单选 -->
        <!-- <el-select
                  v-if="field.type === 3"
                  v-model="customFieldList[field.formCustomFieldIndex].val"
                  :placeholder="field.tip || '请选择'"
                >
                  <el-option
                    v-for="(option, optionIndex) in field.contents"
                    :key="optionIndex"
                    :label="option.val"
                    :value="option.val"
                  ></el-option>
                </el-select> -->

        <!-- 多选 -->
        <!-- <el-select
                  v-if="field.type === 4"
                  v-model="customFieldList[field.formCustomFieldIndex].valList"
                  :placeholder="field.tip || '请选择'"
                  multiple
                >
                  <el-option
                    v-for="(option, optionIndex) in field.contents"
                    :key="optionIndex"
                    :label="option.val"
                    :value="option.val"
                  ></el-option>
                </el-select> -->

        <!-- 评分 -->
        <!-- <el-rate
                  v-if="field.type === 8"
                  :model-value="Number(customFieldList[field.formCustomFieldIndex].val) / 2"
                  @change="(val: number) => customFieldList[field.formCustomFieldIndex].val = String(val * 2)"
                ></el-rate> -->

        <!-- 日期 -->
        <!-- <el-date-picker
                  v-if="field.type === 9"
                  v-model="customFieldList[field.formCustomFieldIndex].val"
                  :placeholder="field.tip || '请选择日期'"
                  @change="handleChangeDate(field.formCustomFieldIndex)"
                ></el-date-picker> -->

        <!-- 日期时间 -->
        <!-- <el-date-picker
                  v-if="field.type === 10"
                  v-model="customFieldList[field.formCustomFieldIndex].val"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm"
                  date-format="MMM DD, YYYY"
                  time-format="HH:mm"
                  :placeholder="field.tip || '请选择日期时间'"
                  @change="handleChangeDateTime(field.formCustomFieldIndex)"
                /> -->
        <!-- </el-form-item> -->
        <!-- </el-form> -->

        <!-- 图片上传 -->
        <!-- <el-form
              v-for="(field, index) in customFieldList.filter((item) => item.type === 5)"
              ref="customFieldFormInstance"
              :key="index"
              :model="customFieldList[field.formCustomFieldIndex]"
              label-position="top"
              inline-message
            >
              <el-form-item
                :label="`${field.name}（最多上传${field.uploadQty}张）`"
                prop="fileList"
                :rules="[
                  {
                    required: field.required,
                    message: field.tip || '请上传图片',
                    trigger: ['blur', 'change'],
                  },
                ]"
              >
                <div class="custom-field-upload">
                  <div v-for="(img, imgIndex) in field.fileList" :key="imgIndex" class="file">
                    <h-image
                      :width="80"
                      :height="50"
                      :initial-index="imgIndex"
                      :preview-src-list="field.fileList.map((item) => item.url)"
                      :padding="2"
                      :src="img.url"
                      @del="handleDelFile(field.formCustomFieldIndex, imgIndex)"
                    ></h-image>
                    <h-tooltip-text
                      :text="img.file.name"
                      :max-width="80"
                      :height="16"
                    ></h-tooltip-text>
                  </div>
                  <el-upload
                    v-if="field.fileList.length < field.uploadQty"
                    class="upload-picture upload-wrapper"
                    multiple
                    accept="image/*"
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="(file: UploadFile) => handleUploadFile(file, field.formCustomFieldIndex)"
                  >
                    <el-icon :size="24" color="#007cff">
                      <upload-filled />
                    </el-icon>
                  </el-upload>
                </div>
              </el-form-item>
            </el-form> -->

        <!-- 附件上传 -->
        <!-- <el-form
              v-for="(field, index) in customFieldList.filter((item) => item.type === 6)"
              ref="customFieldFormInstance"
              :key="index"
              :model="customFieldList[field.formCustomFieldIndex]"
              label-position="top"
              inline-message
            >
              <el-form-item
                :label="`${field.name}（最多上传${field.uploadQty}个）`"
                prop="fileList"
                :rules="[
                  {
                    required: field.required,
                    message: field.tip || '请上传附件',
                    trigger: ['blur', 'change'],
                  },
                ]"
              >
                <div class="custom-field-upload">
                  <div v-for="(pdf, pdfIndex) in field.fileList" :key="pdfIndex" class="file">
                    <h-image
                      :width="80"
                      :height="50"
                      :initial-index="pdfIndex"
                      :is-show-img-preview="false"
                      :padding="2"
                      :src="pdfPlaceholderImg"
                      @preview="
                        handlePdfPreview(
                          field.fileList.map((item) => item.url),
                          pdfIndex,
                        )
                      "
                      @del="handleDelFile(field.formCustomFieldIndex, pdfIndex)"
                    ></h-image>
                    <h-tooltip-text
                      :text="pdf.file.name"
                      :max-width="80"
                      :height="16"
                    ></h-tooltip-text>
                  </div>
                  <el-upload
                    v-if="field.fileList.length < field.uploadQty"
                    class="upload-pdf upload-wrapper"
                    multiple
                    accept=".pdf"
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="(file: UploadFile) => handleUploadFile(file, field.formCustomFieldIndex)"
                  >
                    <el-icon :size="24" color="#007cff">
                      <upload-filled />
                    </el-icon>
                  </el-upload>
                </div>
              </el-form-item>
            </el-form> -->

        <!-- 视频上传 -->
        <!-- <el-form
              v-for="(field, index) in customFieldList.filter((item) => item.type === 7)"
              ref="customFieldFormInstance"
              :key="index"
              :model="customFieldList[field.formCustomFieldIndex]"
              label-position="top"
              inline-message
            >
              <el-form-item
                :label="`${field.name}（最多上传${field.uploadQty}个）`"
                prop="fileList"
                :rules="[
                  {
                    required: field.required,
                    message: field.tip || '请上传视频',
                    trigger: ['blur', 'change'],
                  },
                ]"
              >
                <div class="custom-field-upload">
                  <div v-for="(video, videoIndex) in field.fileList" :key="videoIndex" class="file">
                    <h-image
                      :width="80"
                      :height="50"
                      :initial-index="videoIndex"
                      :is-show-img-preview="false"
                      :padding="2"
                      :src="videoPlaceholderImg"
                      @preview="
                        handleVideoPreview(
                          field.fileList.map((item) => item.url),
                          videoIndex,
                        )
                      "
                      @del="handleDelFile(field.formCustomFieldIndex, videoIndex)"
                    ></h-image>
                    <h-tooltip-text
                      :text="video.file.name"
                      :max-width="80"
                      :height="16"
                    ></h-tooltip-text>
                  </div>
                  <el-upload
                    v-if="field.fileList.length < field.uploadQty"
                    class="upload-video upload-wrapper"
                    multiple
                    accept="video/*"
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="(file: UploadFile) => handleUploadFile(file, field.formCustomFieldIndex)"
                  >
                    <el-icon :size="24" color="#007cff">
                      <upload-filled />
                    </el-icon>
                  </el-upload>
                </div>
              </el-form-item>
            </el-form> -->

        <!-- 多行文本 -->
        <!-- <el-form
              v-for="(field, index) in customFieldList.filter((item) => item.type === 2)"
              ref="customFieldFormInstance"
              :key="index"
              :model="customFieldList[field.formCustomFieldIndex]"
              label-position="top"
              inline-message
            >
              <el-form-item
                :label="field.name"
                prop="val"
                :rules="[
                  {
                    required: field.required,
                    message: field.tip || '请上传视频',
                    trigger: ['blur', 'change'],
                  },
                ]"
              >
                <el-input
                  v-model.trim="customFieldList[field.formCustomFieldIndex].val"
                  :placeholder="field.tip || '请输入'"
                  type="textarea"
                  maxlength="200"
                  show-word-limit
                  resize="both"
                />
              </el-form-item>
            </el-form> -->
        <!-- </div> -->
        <!-- </div> -->

        <!-- 文件查看 -->
        <HDialog v-model="dialogContract" title="查看附件" :width="900">
          <iframe :src="`${file}`" frameborder="0" height="600" width="100%"></iframe>
        </HDialog>

        <!-- 创建公司 -->
        <el-dialog v-model="createUserDialogVisit" :draggable="true" title="创建公司" width="400px">
          <el-form
            ref="createUserRef"
            :model="createUserForm"
            :rules="createUserFormRules"
            label-position="left"
            label-width="90px"
          >
            <el-form-item label="公司姓名" prop="name">
              <el-input v-model.trim="createUserForm.name" clearable placeholder="请输入公司姓名" />
            </el-form-item>
            <el-form-item label="公司手机号" prop="phone">
              <el-input
                v-model.trim="createUserForm.phone"
                clearable
                maxlength="11"
                placeholder="请输入公司手机号"
                @input="createUserForm.phone = createUserForm.phone.replace(/[^0-9]/g, '')"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="createUserDialogVisit = false">取消</el-button>
              <el-button class="btn-bg2" @click="onSaveCreateUser(createUserRef)">保存</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>

    <video-preview
      v-model:visible="videoPreviewModalVisible"
      :video-list="videoPreviewUrls"
      :initial-index="videoPreviewInitialIndex"
    />

    <pdf-preview
      v-model:visible="pdfPreviewModalVisible"
      :initial-index="pdfPreviewInitialIndex"
      :pdf-list="pdfPreviewUrls"
    />
  </div>
</template>

<script lang="ts" setup>
  import { computed, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
  import { UploadFilled } from '@element-plus/icons-vue'
  // import pdfPlaceholderImg from '@/assets/image/pdf.png'
  import type { FormInstance, FormRules, UploadFile, UploadRawFile } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { useRouter } from 'vue-router'
  import {
    addSave,
    getModuleField,
    // getUserSelect,
    workLevelPageSelect,
    workModulePageSelect,
    workModuleTypePageSelect,
    workModuleWayPageSelect,
    getOrganType,
  } from '@/api/order'
  import { getLoginAccountNetworkId, getNetworkPageSelect } from '@/api/network'
  import { empPageSelecct } from '@/api/organize'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import { orderAnnexUpload } from '@/api/upload'
  import { useSettingStore } from '@/store/modules/setting'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import _ from 'lodash'
  import { CustomField, Form, OrderType } from './types'
  import useAddrParseService from '@/views/order/new/services/useAddrParseService'
  // import useRepeatOrder from '@/views/order/new/services/useRepeatOrder'
  // import videoPlaceholderImg from '@/assets/image/pages/order/new/video.png'
  import { HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import GoodInfo from './components/good-info/index.vue'
  import { ElIcon } from 'element-plus'
  import routeComponentName from '@/config/route-component-name'
  // import moment from 'moment'
  // import { useGetFaultTypes } from '@/services/pages/know/fault/useFaultType'
  import { useGetFaultByType } from '@/services/pages/know/useFault'
  import { getFaultByType } from '@/api/knowledge'
  import VideoPreview from '@/views/return-factory/repair/form/components/custom-info/VideoPreview.vue'
  import PdfPreview from '@/views/return-factory/repair/form/components/custom-info/PdfPreview.vue'
  import {
    // useGetUserCreditLimit,
    useGetMainContactPersonOptionList,
  } from '@/services/pages/user/useUser'
  import { useUserStore } from '@/store/modules/user'
  import { verifyPhone } from '@/utils/validate'
  import { useGetDepartmentOptions } from '@/services/module/department/useOptions'
  import departmentFixedData from '@/config/fixed-data/department/department'
  import { useGetOrderSaveFaultTypeOptions } from '@/services/module/order/useSave'
  import { TableDataGoodInfoOrderCreate } from './components/good-info/types'
  import { useOrderCopy } from '@/store/modules/orderCopy'
  import { useGetOrderSourceList } from '@/services/pages/order/useSoruce'

  const {
    list: workSourceList,
    getListLoading: getWorkSourceListLoading,
    getList: getWorkSourceList,
  } = useGetOrderSourceList()
  const {
    options: departmentOptions,
    getOptionsLoading: getDepartmentOptionsLoading,
    getOptions: getDepartmentOptions,
  } = useGetDepartmentOptions()
  const {
    optionList: userOptionList,
    getOptionListParam: getUserOptionListParam,
    getOptionListLoading: getUserOptionListLoading,
    getOptionList: getUserOptionList,
  } = useGetMainContactPersonOptionList()
  const {
    optionList: sendRepairUserOptionList,
    getOptionListParam: getSendRepairUserOptionListParam,
    getOptionListLoading: getSendRepairUserOptionListLoading,
    getOptionList: getSendRepairUserOptionList,
  } = useGetMainContactPersonOptionList()
  const { addrParseResult, addrParse } = useAddrParseService
  // const { getRepeatOrderSetFun, repeatOrderObj, getRepeatOrderFun, is_RepeatOrder } = useRepeatOrder
  // const { faultTypes, getFaultTypesLoading, getFaultTypes } = useGetFaultTypes()
  const {
    // loading: getFaultByTypeLoading,
    // faultList,
    getFaultParams,
    getFault,
  } = useGetFaultByType()
  // const { userCreditLimitByOrderTip, getCreditLimit } = useGetUserCreditLimit()
  const {
    faultTypeOptions,
    getFaultTypeOptionsKeyword,
    getFaultTypeOptionsLoading,
    getFaultTypeOptions,
  } = useGetOrderSaveFaultTypeOptions()
  const { orderDetailToPaste, orderGoodListToPaste, clearCopyInfo } = useOrderCopy()

  defineOptions({
    name: routeComponentName.order.orderCreate,
  })

  // 是否禁用客户输入
  const isDisabledUserInput = ref(false)
  const allLoading = computed(() => {
    return (
      submitLoading.value ||
      getDepartmentOptionsLoading.value ||
      loading.value ||
      getFaultTypeOptionsLoading.value ||
      getSendRepairUserOptionListLoading.value ||
      getUserOptionListLoading.value ||
      getOrganTypeInfoLoading.value ||
      getLoginedNetworkIdLoading.value ||
      getCustomerOptionsLoading.value ||
      getWorkSourceListLoading.value
    )
  })

  // 销售渠道下拉选项
  const saleChannelOptionList = [
    { value: 1, label: '天猫' },
    { value: 2, label: '抖音' },
    { value: 3, label: '线下' },
    { value: 4, label: '商用' },
  ]

  // 家用销售渠道额外下拉选项
  const saleChannelOptionList2 = [
    { value: 5, label: '京东' },
    { value: 6, label: '小红书' },
  ]

  // 销售类型下拉选项
  const serviceTypeOptionList = [
    { value: 1, label: '维修' },
    { value: 2, label: '安装' },
    { value: 3, label: '调试' },
    { value: 4, label: '保养' },
    { value: 5, label: '技术支持' },
  ]

  // 1=维修、2=翻新、3=检测、4=安装、5=保养、6=报废评估、7=其他
  //  销售类型下拉选项
  const serviceTypeOptionList2 = [
    { value: 1, label: '维修' },
    { value: 2, label: '翻新' },
    { value: 3, label: '检测' },
    { value: 4, label: '安装' },
    { value: 5, label: '保养' },
    { value: 6, label: '报废评估' },
    { value: 7, label: '其他' },
  ]

  // 服务方式下拉选项
  const serviceModeOptionList = [
    { value: 1, label: '上门' },
    { value: 2, label: '远程' },
    { value: 3, label: '返厂' },
  ]

  // 责任归属下拉选项
  const dutyBelongToOptionList = [
    { value: 1, label: '工厂问题' },
    { value: 2, label: '客人问题' },
  ]
  // 责任归属下拉选项（家用才有）
  const dutyBelongToOptionList2 = [
    { value: 3, label: '材料问题' },
    { value: 4, label: '运输问题' },
  ]

  // 用户状态管理
  const userStore = useUserStore()

  // 视频预览路径集合
  const videoPreviewUrls = ref<Array<string>>([])

  // 视频预览的初始索引
  const videoPreviewInitialIndex = ref(0)

  // 视频预览弹窗显示状态
  const videoPreviewModalVisible = ref(false)

  // 附件预览路径集合
  const pdfPreviewUrls = ref<Array<string>>([])

  // 附件预览的初始索引
  const pdfPreviewInitialIndex = ref(0)

  // 附件预览弹窗显示状态
  const pdfPreviewModalVisible = ref(false)

  // 产品列表组件实例
  const goodInfoInstance = ref<InstanceType<typeof GoodInfo> | null>(null)

  // 全局路由对象
  const router = useRouter()

  // 自定义字段
  const customFieldList = ref<Array<CustomField>>([])

  // 自定义字段表单组件实例
  // const customFieldFormInstance = ref<Array<FormInstance> | null>(null)

  // 基本信息表单组件实例
  const basicInfoFormInstance = ref<FormInstance | null>(null)

  // 基本信息div
  const basicInfoDiv = ref<HTMLDivElement | null>(null)

  // 自定义信息div
  // const customInfoDiv = ref<HTMLDivElement | null>(null)

  // 公司信息div
  const customerInfoDiv = ref<HTMLDivElement | null>(null)

  // 产品信息div
  const goodInfoDiv = ref<HTMLDivElement | null>(null)

  // 表单
  const basicData = ref<Form>({
    source: 1,
    moduleId: '', // 工单类型
    overinsured: false, // 质保状态
    content: '', // 故障描述
    userId: '', // 公司ID
    accountNo: '', // 公司账号
    name: '', // 姓名
    phone: '', // 公司手机号
    otherPhone: '', // 其他联系方式
    address: '', // 详细地址
    factoryId: '', // 品牌商家ID
    businessPhone: '',
    customfieldList: [
      {
        contents: [{ id: null, val: null }],
        moduleFieldId: '',
        name: '',
        required: true,
        status: null,
        tip: '',
        type: null,
        uploadQty: null,
        uploadSize: null,
        val: null,
        imgArr: [],
        workFieldId: '',
      },
    ],
    faultTypeRelationVos: [],
    faultRelationVos: [],
    faultReason: [],
    solution: [],
    sendForRepairUsername: '', //送修人
    sendForRepairPhone: '', //送修人手机
    repairCompany: '',
    repairCompanyId: '',
    repairCompanyPhone: '',
    workGoodsType: 1,
    saleChannel: 1,
    buyPlatformOrderNo: '',
    accountability: 1,
    serviceType: 1,
    serviceMode: 1,
    remark: '',
    orderReservationEndTime: '',
    orderReservationstartTime: '',
    storeName: '',
    orderReservationDate: '',
    departmentId: '',
    empId: '',
    workSourceId: '',
  })

  // 获取客户下拉选项加载
  const getCustomerOptionsLoading = ref(false)

  // 客户下拉选项列表
  const customerOptions = ref()

  // 解决措施下拉选项
  const solveOptions = ref<Array<{ id: string; content: string }>>([])

  // 故障原因下拉选项
  const faultReasonOptions = ref<Array<{ id: string; content: string }>>([])

  // 选择的用户是否加入了黑名单
  const isSelectedUserJoinBlackList = ref(false)

  // 当前登录的账号所在的网点
  const loginedAccountNetwork = ref('')

  // 送修公司弹出框显示状态
  // const sendRepairUserPopoverStatus = ref(false)

  /**
   * 故障类型搜索事件
   * @param {string} keyword - 搜索关键字
   */
  const handleFaultTypeOptionsSearch = _.debounce((keyword: string) => {
    if (getFaultTypeOptionsKeyword.value !== keyword) {
      getFaultTypeOptionsKeyword.value = keyword
      getFaultTypeOptions()
    }
  }, 500)

  /**
   * 清除预约时间
   */
  const onClearAppointmentTime = () => {
    basicData.value.orderReservationDate = ''
    basicData.value.orderReservationstartTime = ''
    basicData.value.orderReservationEndTime = ''
  }

  /**
   * 故障现象描述快速填充项点击事件
   * @param {string} text - 快读填充项文本
   */
  // const handleDescQuickFillItemClick = (text: string) => {
  //   if (basicData.value.content.length < 200) {
  //     basicData.value.content += `${text}、`
  //   }

  //   if (basicData.value.content.length > 200) {
  //     basicData.value.content = basicData.value.content.substring(0, 200)
  //   }
  // }

  /**
   * 送修公司更新事件
   * @param {UserMainContactPersonOption} sendRepairUser - 送修公司
   */
  // const handleSendRepairUserChange = (sendRepairUser: UserMainContactPersonOption) => {
  //   basicData.value.repairCompany = sendRepairUser.name
  //   basicData.value.repairCompanyId = sendRepairUser.userId
  //   basicData.value.repairCompanyPhone = sendRepairUser.phone
  // }

  /**
   * 清除送修公司信息事件
   */
  // const onClearSendRepairUserInfo = () => {
  //   basicData.value.repairCompanyId = ''
  //   basicData.value.repairCompany = ''
  //   basicData.value.repairCompanyPhone = ''
  //   customerSelectPopoverVisible.value = false
  // }

  /**
   * 送修公司输入事件
   */
  // const onSendRepairUserInput = _.debounce(() => {
  //   getSendRepairUserOptionListParam.value.name = basicData.value.repairCompany
  //   getSendRepairUserOptionList()
  //   sendRepairUserPopoverStatus.value = true
  // }, 500)

  /**
   * 商品信息的更新客户事件
   * @param {CodeInfoByCode} goodAndUserInfo - 客户和商品信息
   */
  const handleGoodInfoChangeUser = (goodAndUserInfo: CodeInfoByCode) => {
    if (goodAndUserInfo) {
      nextTick(() => {
        addrs.value = {
          province: goodAndUserInfo.province,
          city: goodAndUserInfo.city,
          area: goodAndUserInfo.area,
          town: goodAndUserInfo.town,
        }

        if (goodAndUserInfo.userId) {
          basicData.value.userId = goodAndUserInfo.userId
        }

        if (goodAndUserInfo.name) {
          basicData.value.name = goodAndUserInfo.name
        }

        if (goodAndUserInfo.phone) {
          basicData.value.phone = goodAndUserInfo.phone
        }

        if (goodAndUserInfo.address) {
          basicData.value.address = goodAndUserInfo.address
        }
      })
    }
  }

  /**
   * 附件预览事件
   * @param {Array<string>} urls - 预览路径集合
   * @param {Number} index - 第一个预览文件的索引
   */
  // const handlePdfPreview = (urls: Array<string>, index: number) => {
  //   pdfPreviewUrls.value = urls
  //   pdfPreviewInitialIndex.value = index
  //   pdfPreviewModalVisible.value = true
  // }

  /**
   * 视频预览事件
   * @param {Array<string>} urls - 预览路径集合
   * @param {Number} index - 第一个预览文件的索引
   */
  // const handleVideoPreview = (urls: Array<string>, index: number) => {
  //   videoPreviewUrls.value = urls
  //   videoPreviewInitialIndex.value = index
  //   videoPreviewModalVisible.value = true
  // }

  /**
   * 组件名称选择事件
   * @param {Array<string>} value - 分类id
   */
  const handleFaultTypeSelect = (value: string) => {
    basicData.value.faultTypeRelationVos = [
      {
        oneFaultTypeId: value,
        twoFaultTypeId: '',
        threeFaultTypeId: '',
      },
    ]
    getFaultParams.value = basicData.value.faultTypeRelationVos
    getFault()
  }

  /**
   * 移除组件名称事件
   * @param {String} val - 分类id
   */
  const handleRemoveFaultType = async (val: string) => {
    getFaultParams.value = [
      {
        oneFaultTypeId: val,
        twoFaultTypeId: '',
        threeFaultTypeId: '',
      },
    ]
    const res = await getFaultByType(getFaultParams.value)
    res.data.data.rows.forEach((item) => {
      removeFaultReasonVoById(item)
    })
  }

  /**
   * 根据故障对象移除故障现象
   * @param {FaultByType} fault - 故障对象
   */
  const removeFaultReasonVoById = (fault: FaultByType) => {
    const faultIndex = basicData.value.faultRelationVos.findIndex(
      (item) => item.faultId === fault.id,
    )
    basicData.value.faultRelationVos.splice(faultIndex, 1)
    removeSolveByIds(fault.solution.map((item) => item.id))
    removeReasonByIds(fault.faultReason.map((item) => item.id))
  }

  /**
   * 根据id列表移除解决措施下拉选项和表单选中的解决措施
   * @param {Array<string>} ids - 解决措施id集合
   */
  const removeSolveByIds = (ids: Array<string>) => {
    solveOptions.value = solveOptions.value.filter((item) => !ids.includes(item.id))
    basicData.value.solution = basicData.value.solution.filter((item) => !ids.includes(item.id))
  }

  /**
   * 根据id列表移除故障原因下拉选项和表单选中的故障原因
   * @param {Array<string>} ids - 解决措施id集合
   */
  const removeReasonByIds = (ids: Array<string>) => {
    faultReasonOptions.value = faultReasonOptions.value.filter((item) => !ids.includes(item.id))
    basicData.value.faultReason = basicData.value.faultReason.filter(
      (item) => !ids.includes(item.id),
    )
  }

  /**
   * 故障现象选择事件
   * @param {Array<string>} value - 选择的值
   */
  // const handleFaultPhenomenonChange = (value: Array<string>) => {
  //   basicData.value.faultRelationVos.length = 0
  //   value.forEach((id) => {
  //     faultPhenomenonOptionsAdd(id)
  //   })
  // }

  /**
   * 故障现象移除事件
   * @param {String} id - 故障现象id
   */
  // const handleFaultPhenomenonRemove = (id: string) => {
  //   const faultOption = faultList.value.find((item) => item.id === id)
  //   if (faultOption) {
  //     removeSolveByIds(faultOption.solution.map((item) => item.id))
  //     removeReasonByIds(faultOption.faultReason.map((item) => item.id))
  //   }
  // }

  /**
   * 添加故障原因下拉选项
   */
  // const faultReasonOptionsAdd = (options: Array<{ id: string; content: string }>) => {
  //   options.forEach((option) => {
  //     if (!faultReasonOptions.value.map((item) => item.id).includes(option.id)) {
  //       if (option.content) {
  //         faultReasonOptions.value.push(option)
  //       }
  //     }
  //   })
  // }

  /**
   * 添加解决措施下拉选项
   */
  // const solveOptionsAdd = (options: Array<{ id: string; content: string }>) => {
  //   options.forEach((option) => {
  //     if (!solveOptions.value.map((item) => item.id).includes(option.id)) {
  //       if (option.content) {
  //         solveOptions.value.push(option)
  //       }
  //     }
  //   })
  // }

  /**
   * 根据故障id添加故障下拉选项并更新表单
   * @param {String} id - 要添加的id
   */
  // const faultPhenomenonOptionsAdd = (id: string) => {
  //   const fault = faultList.value.find((fault) => fault.id === id)
  //   if (fault) {
  //     faultReasonOptionsAdd(fault.faultReason)
  //     solveOptionsAdd(fault.solution)
  //     const isCanAdd = !basicData.value.faultRelationVos
  //       .map((relation) => relation.faultId)
  //       .includes(fault.id)
  //     if (isCanAdd) {
  //       basicData.value.faultRelationVos.push({
  //         faultId: fault.id,
  //         fault: fault.name,
  //       })
  //     }
  //   } else {
  //     basicData.value.faultRelationVos.push({
  //       faultId: `${faultList.value.length}`,
  //       fault: id,
  //     })
  //     faultList.value.push({
  //       code: '',
  //       disabled: false,
  //       faultReason: [],
  //       id: `${faultList.value.length}`,
  //       name: id,
  //       select: true,
  //       solution: [],
  //     })
  //   }
  // }

  /**
   * 故障原因选择事件
   * @param {Array<string>} ids - 选择的故障原因
   */
  // const handleFaultReasonSelect = (ids: Array<string>) => {
  //   basicData.value.faultReason.length = 0
  //   ids.forEach((id) => {
  //     const faultReason = faultReasonOptions.value.find((item) => item.id === id)
  //     if (faultReason) {
  //       basicData.value.faultReason.push(faultReason)
  //     } else {
  //       basicData.value.faultReason.push({
  //         id: `${faultReasonOptions.value.length}`,
  //         content: `${id}`,
  //       })
  //       faultReasonOptions.value.push({
  //         id: `${faultReasonOptions.value.length}`,
  //         content: `${id}`,
  //       })
  //     }
  //   })
  // }

  /**
   * 解决措施选择事件
   * @param {Array<string>} ids - 选择的解决措施
   */
  // const handleSolveSelect = (ids: Array<string>) => {
  //   basicData.value.solution.length = 0
  //   ids.forEach((id) => {
  //     const solve = solveOptions.value.find((item) => item.id === id)
  //     if (solve) {
  //       basicData.value.solution.push(solve)
  //     } else {
  //       basicData.value.solution.push({
  //         id: `${solveOptions.value.length}`,
  //         content: `${id}`,
  //       })
  //       solveOptions.value.push({
  //         id: `${solveOptions.value.length}`,
  //         content: `${id}`,
  //       })
  //     }
  //   })
  // }

  /**
   * 地址识别按钮点击事件
   */
  const addrParseLoading = ref(false)
  const onAddrParse = async () => {
    if (!allUserInfo.value.trim()) return
    addrParseLoading.value = true
    await addrParse(allUserInfo.value.trim())
    addrParseLoading.value = false
    addrs.value = {
      province: addrParseResult.value.province,
      city: addrParseResult.value.city,
      area: addrParseResult.value.area,
      town: addrParseResult.value.town,
    }
    if (basicData.value.departmentId === departmentFixedData.business) {
      basicData.value.userId = ''
      basicData.value.name = addrParseResult.value.username
      basicData.value.phone = addrParseResult.value.phone
      basicData.value.businessPhone = addrParseResult.value.phone
    } else {
      basicData.value.repairCompany = addrParseResult.value.username
      basicData.value.repairCompanyPhone = addrParseResult.value.phone
    }
    basicData.value.address = addrParseResult.value.address
  }

  /**
   * 显示文件上传的大小错误
   */
  // const showFileUploadSizeErrTip = _.debounce((customField: CustomField) => {
  //   let tip = ''
  //   if (customField.type === 5) {
  //     tip = infoTip.order.create.picture_upload_size_err
  //   }

  //   if (customField.type === 6) {
  //     tip = infoTip.order.create.pdf_upload_size_err
  //   }

  //   if (customField.type === 7) {
  //     tip = infoTip.order.create.video_upload_size_err
  //   }
  //   HMessageBox.error(tip.replace('$size', String(customField.uploadSize)))
  // }, 10)

  /**
   * 显示文件上传的数量错误
   */
  // const showFileUploadCountErrTip = _.debounce((customField: CustomField) => {
  //   let tip = ''
  //   if (customField.type === 5) {
  //     tip = infoTip.order.create.picture_upload_count_err
  //   }

  //   if (customField.type === 6) {
  //     tip = infoTip.order.create.pdf_upload_count_err
  //   }

  //   if (customField.type === 7) {
  //     tip = infoTip.order.create.video_upload_count_err
  //   }
  //   HMessageBox.error(tip.replace('$num', String(customField.uploadQty)))
  // }, 10)

  /**
   * 显示文件上传的类型错误
   */
  // const showFileUploadTypeErrTip = _.debounce((customField: CustomField) => {
  //   let tip = ''
  //   if (customField.type === 5) {
  //     tip = infoTip.order.create.picture_upload_type_err
  //   }

  //   if (customField.type === 6) {
  //     tip = infoTip.order.create.pdf_upload_type_err
  //   }

  //   if (customField.type === 7) {
  //     tip = infoTip.order.create.video_upload_type_err
  //   }
  //   HMessageBox.error(tip)
  // }, 10)

  /**
   * 文件上传事件
   * @param {UploadFile} file - 文件对象
   * @param {Number} index - 表单索引
   */
  // const handleUploadFile = (file: UploadFile, index: number) => {
  //   const customField = customFieldList.value[index]
  //   if (file.raw.size / 1024 / 1024 > customField.uploadSize) {
  //     showFileUploadSizeErrTip(customField)
  //     return
  //   }

  //   if (customField.fileList.length >= customField.uploadQty) {
  //     showFileUploadCountErrTip(customField)
  //     return
  //   }

  //   if (customField.type === 5 && !file.raw.type.includes('image')) {
  //     showFileUploadTypeErrTip(customField)
  //     return
  //   }

  //   if (customField.type === 6 && !file.raw.type.includes('pdf')) {
  //     showFileUploadTypeErrTip(customField)
  //     return
  //   }

  //   if (customField.type === 7 && !file.raw.type.includes('video')) {
  //     showFileUploadTypeErrTip(customField)
  //     return
  //   }

  //   customFieldList.value[index].fileList.push({
  //     file: file.raw,
  //     url: URL.createObjectURL(file.raw),
  //   })
  // }

  /**
   * 删除文件
   * @param {Number} formIndex - 表单索引
   * @param {Number} fileIndex - 文件索引
   */
  // const handleDelFile = (formIndex: number, fileIndex: number) => {
  //   customFieldList.value[formIndex].fileList.splice(fileIndex, 1)
  // }

  /**
   * 日期更新事件
   * @param {Number} formIndex - 表单索引
   */
  // const handleChangeDate = (formIndex: number) => {
  //   const date = customFieldList.value[formIndex].val
  //   customFieldList.value[formIndex].val = moment(date).format('YYYY-MM-DD')
  // }

  /**
   * 日期事件更新事件
   * @param {Number} formIndex - 表单索引
   */
  // const handleChangeDateTime = (formIndex: number) => {
  //   const dateTime = customFieldList.value[formIndex].val
  //   customFieldList.value[formIndex].val = moment(dateTime).format('YYYY-MM-DD HH:mm')
  // }

  const SettingStore = useSettingStore()

  /**
   * 刷新页面
   */
  const refresh = () => {
    SettingStore.setReload()
  }

  // 客户表单组件实例
  const customerInfoFormInstance = ref<FormInstance | null>(null)
  const singleAddressRef = ref<InstanceType<typeof SingleAddress> | null>(null) //地址dom

  // const CascaderProps = ref({
  //   value: 'id',
  //   label: 'name',
  //   children: 'selectVos',
  //   disabled: 'select',
  //   checkStrictly: true,
  // })
  const formRef = ref<FormInstance>()
  const submitLoading = ref(false) //提交工单loading
  // const showType = ref(false)
  const grades = ref(null) // 服务级别
  const grade = ref(null) // 服务级别
  const method = ref() // 处理方式
  const network = ref() // 受理网点
  const now = ref(null) // 下单时间
  const fileList = ref([])
  const type = ref(null) // 工单模块分类

  // 产品故障图文件对象
  const goodFaultImgFile = ref<{ url: string; file: UploadRawFile | null }>({
    url: '',
    file: null,
  })

  // 产品条码图文件对象
  const goodCodeImgFile = ref<{ url: string; file: UploadRawFile | null }>({
    url: '',
    file: null,
  })

  // 工单模块下拉选项
  const modules = ref<Array<OrderType>>([])

  const loading = ref(false)
  const types = ref(null) //工单模块分类
  const dialogContract = ref(false) //文件查看弹窗
  const file = ref() //文件
  const methodss = ref(null) // 处理方式
  const networks = ref(null)
  const addrs = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })
  const submitFormShow = ref(false) //用来判断是否有自定义字段
  const createUserDialogVisit = ref(false) // 创建公司弹窗
  const createUserRef = ref()
  // 创建公司对象
  const createUserForm = reactive({
    name: '', // 公司姓名
    phone: '', // 公司手机号
  })

  // 校验规则
  const rules = computed(() => {
    return {
      moduleId: [{ required: true, message: '请选择工单类型', trigger: ['change', 'blur'] }],
      workSourceId: [{ required: true, message: '请选择工单来源', trigger: ['change', 'blur'] }],
      overinsured: [{ required: true, message: '请选择质保状态', trigger: ['change', 'blur'] }],
      // phone: [
      //   { required: true, message: '请输入公司手机号', trigger: ['change', 'blur'] },
      //   {
      //     validator: (rule, value, callback) => {
      //       if (!/^1[3,4,5,6,7,8,9][0-9]{9}$/.test(basicData.value.phone)) {
      //         return callback(new Error('手机号格式错误'))
      //       }
      //       callback()
      //     },
      //     trigger: ['change', 'blur'],
      //   },
      // ],
      name: [
        {
          required: true,
          message: `请输入${
            basicData.value.departmentId === departmentFixedData.family ? '店铺/渠道' : '客户姓名'
          }`,
          trigger: ['change', 'blur'],
        },
      ],
      // address: [{ required: true, message: '请输入详细地址', trigger: ['change', 'blur'] }],
      sendForRepairUsername: [
        { required: true, message: '请输入反馈人', trigger: ['change', 'blur'] },
      ],
      sendForRepairPhone: [
        { required: true, message: '请输入反馈电话', trigger: ['change', 'blur'] },
        {
          validator: (rule, value, callback) => {
            if (!verifyPhone(basicData.value.sendForRepairPhone)) {
              return callback(new Error('反馈电话格式错误'))
            }
            callback()
          },
          trigger: ['change', 'blur'],
        },
      ],
      // repairCompany: [
      //   {
      //     required: true,
      //     message: '请选择送修公司',
      //     trigger: ['change', 'blur'],
      //   },
      // ],
      factoryId: [{ required: true, message: '请选择商家', trigger: ['change', 'blur'] }],
      customerAddress: [
        {
          validator: (rule, value, callback) => {
            if (!singleAddressRef.value) {
              callback(new Error('请选择所在地区'))
              return
            }
            const { province, area, city } = singleAddressRef.value.getSelectAddr()
            if (!province || !area || !city) {
              callback(new Error('请选择所在地区'))
              return
            }
            callback()
          },
          trigger: ['change', 'blur'],
        },
      ],
      workGoodsType: [{ required: true, message: '请选择产品类型', trigger: ['change', 'blur'] }],
      storeName: [
        {
          required: basicData.value.departmentId === departmentFixedData.business,
          message: '请输入店名',
          trigger: ['change', 'blur'],
        },
      ],
      accountability: [{ required: true, message: '请选择责任归属', trigger: ['change', 'blur'] }],
      serviceType: [{ required: true, message: '请选择服务类型', trigger: ['change', 'blur'] }],
      serviceMode: [{ required: true, message: '请选择服务方式', trigger: ['change', 'blur'] }],
      source: [{ required: true, message: '请选择工单来源', trigger: ['change', 'blur'] }],
      // content: [{ required: true, message: '请输入问题描述', trigger: ['change', 'blur'] }],
      phone: [{ required: true, message: '请输入业务手机号', trigger: ['change', 'blur'] }],
      businessPhone: [
        {
          required: true,
          message:
            basicData.value.departmentId === departmentFixedData.business
              ? '请输入业务手机号'
              : '请输入客户手机号',
          trigger: ['change', 'blur'],
        },
      ],
      repairCompany: [
        {
          required: true,
          message: `${
            basicData.value.departmentId === departmentFixedData.family ? '联系人' : '反馈人'
          }不能为空`,
          trigger: ['change', 'blur'],
        },
      ],
      address: [{ required: true, message: '请输入详细地址', trigger: ['change', 'blur'] }],
      repairCompanyPhone: [
        {
          required: true,
          message: `${
            basicData.value.departmentId === departmentFixedData.family ? '联系方式' : '反馈电话'
          }不能为空`,
          trigger: ['change', 'blur'],
        },
      ],
      faultTypeRelationVos: [
        { required: true, message: '请选择故障类型(反馈故障)', trigger: ['change', 'blur'] },
        {
          validator: (rule, value, callback) => {
            if (basicData.value.faultTypeRelationVos.length <= 0) {
              return callback(new Error('请选择故障类型(反馈故障)'))
            }
            callback()
          },
          trigger: ['change', 'blur'],
        },
      ],
      // faultRelationVos: [
      //   { required: true, message: '请选择故障现象', trigger: ['change', 'blur'] },
      //   {
      //     validator: (rule, value, callback) => {
      //       if (basicData.value.faultRelationVos.length <= 0) {
      //         return callback(new Error('请选择故障现象'))
      //       }
      //       callback()
      //     },
      //     trigger: ['change', 'blur'],
      //   },
      // ],
      // faultReason: [
      //   { required: true, message: '请选择故障原因', trigger: ['change', 'blur'] },
      //   {
      //     validator: (rule, value, callback) => {
      //       if (basicData.value.faultReason.length <= 0 || !basicData.value.faultReason) {
      //         return callback(new Error('请选择故障原因'))
      //       }
      //       callback()
      //     },
      //     trigger: ['change', 'blur'],
      //   },
      // ],
      // solution: [
      //   { required: true, message: '请选择解决措施', trigger: ['change', 'blur'] },
      //   {
      //     validator: (rule, value, callback) => {
      //       if (basicData.value.solution.length <= 0 || !basicData.value.solution) {
      //         return callback(new Error('请选择解决措施'))
      //       }
      //       callback()
      //     },
      //     trigger: ['change', 'blur'],
      //   },
      // ],
      departmentId: [{ required: true, message: '请选择产品类型', trigger: ['change', 'blur'] }],
      content: [
        {
          required: basicData.value.departmentId === departmentFixedData.family,
          message: '请输入故障类型',
          trigger: ['change', 'blur'],
        },
      ],
    }
  })

  // 校验规则
  const createUserFormRules = reactive<FormRules>({
    name: [
      { required: true, message: '公司姓名不能为空', trigger: ['change', 'blur'] },
      { required: true, max: 100, message: '公司姓名长度限制 2~100', trigger: ['change', 'blur'] },
    ],
    phone: [
      { required: true, message: '公司手机号不能为空', trigger: ['change', 'blur'] },
      {
        required: true,
        validator: (rule, value, callback) => {
          if (!verifyPhone(createUserForm.phone)) {
            return callback(new Error('手机号格式错误'))
          }
          callback()
        },
        trigger: ['change'],
      },
    ],
  })

  /**
   * 产品故障图删除事件
   */
  // const onDelGoodFaultImgFile = () => {
  //   goodFaultImgFile.value = {
  //     url: '',
  //     file: null,
  //   }
  // }

  /**
   * 产品条码图删除事件
   */
  // const onDelGoodSnCodeImgFile = () => {
  //   goodCodeImgFile.value = {
  //     url: '',
  //     file: null,
  //   }
  // }

  // 取消工单
  const onCancelOrder = () => {
    useTagsViewStore().delView(router.currentRoute.value.path)
    router.push({ path: '/order/list' })
  }

  /**
   * 重单字段查询
   */
  const repeatSearch = ref({
    codeIds: [], //产品条码
    goodsIds: [], //产品IDs
    moduleId: '', //模块ID
    userPhone: '', //公司手机号
    username: '', //公司姓名
  })
  // /**
  //  * 重单开启字段
  //  */
  // const repeatOrderObj = ref({
  //   enableGoodsModel: true,//型号
  //   enableGoodsName: false,//产品名称
  //   enableOrderModule: false,//工单模块
  //   enableSNCode: false,//条码、条码
  //   enableUserName: true,//公司名称
  //   enableUserPhone: true//公司手机号
  // })
  // // 获取是否开启重单
  // const getRepeatOrderSetFun = () => {
  //   getRepeatOrderSet().then(res => {
  //     if (res.data.code == 20000) {
  //       repeatOrderObj.value = res.data.data.row
  //     }
  //   })
  // }
  // 工单模块
  // watch(
  //   () => basicData.value.moduleId,
  //   async (n) => {
  //     await getRepeatOrderSetFun()
  //     if (repeatOrderObj.value.enableOrderModule) {
  //       repeatSearch.value.moduleId = n
  //       if (repeatSearch.value.moduleId) is_RepeatOrderArr.value.push(5)
  //       is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
  //       if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort()))
  //         // getRepeatOrderFun(repeatSearch.value, true)
  //     }
  //   },
  // )
  // 公司手机号, 公司姓名
  // watch([() => basicData.value.phone, () => basicData.value.name], (n) => {
  //   customerInfoFormInstance.value.validateField(['phone', 'name'], async (v) => {
  //     if (v) {
  //       await getRepeatOrderSetFun()
  //       is_RepeatOrderArr.value = is_RepeatOrderArr.value.filter((o) => !(o == 3 || o == 4))
  //       if (repeatOrderObj.value.enableUserPhone && repeatOrderObj.value.enableUserName) {
  //         repeatSearch.value.userPhone = n[0]
  //         repeatSearch.value.username = n[1]
  //         if (repeatSearch.value.userPhone) is_RepeatOrderArr.value.push(4)
  //         if (repeatSearch.value.username) is_RepeatOrderArr.value.push(3)
  //         is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
  //         if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort()))
  //           getRepeatOrderFun(repeatSearch.value, true)
  //       } else if (repeatOrderObj.value.enableUserName) {
  //         repeatSearch.value.username = n[1]
  //         if (repeatSearch.value.username) is_RepeatOrderArr.value.push(3)
  //         is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
  //         if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort()))
  //           getRepeatOrderFun(repeatSearch.value, true)
  //       } else if (repeatOrderObj.value.enableUserPhone) {
  //         repeatSearch.value.userPhone = n[0]
  //         if (repeatSearch.value.userPhone) is_RepeatOrderArr.value.push(4)
  //         is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
  //         if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort()))
  //           getRepeatOrderFun(repeatSearch.value, true)
  //       }
  //     }
  //   })
  // })
  // //型号、产品名称=>1 条码、条码=>2  公司名称=>3 公司手机号=>4 工单模块=>5
  const is_RepeatOrderArr = ref([])

  /**
   * 产品信息选择产品事件
   */
  const onGoodInfoChangeGoodList = async () => {
    // await getRepeatOrderSetFun()
    let codeIds = []
    let goodsIds = []
    is_RepeatOrderArr.value = is_RepeatOrderArr.value.filter((o) => !(o == 1 || o == 2))
    if (!goodInfoInstance.value) {
      return
    }
    const orderGoods = goodInfoInstance.value.getGoods()
    orderGoods.map((o) => {
      o.orderGoodsVos.map((i) => {
        if (i.codeIds.length > 0) {
          codeIds.push(...i.codeIds)
        }
        if (i.goodsId) {
          goodsIds.push(i.goodsId)
        }
      })
    })
    orderGoods.forEach((orderGood) => {
      if (orderGood.type === 1) {
        const firstOrderGoodVo = orderGood.orderGoodsVos[0]
        let isAllGoodUserSame = true
        orderGood.orderGoodsVos.forEach((orderGoodVo) => {
          if (
            firstOrderGoodVo.userId !== orderGoodVo.userId ||
            firstOrderGoodVo.name !== orderGoodVo.name ||
            firstOrderGoodVo.phone !== orderGoodVo.phone ||
            firstOrderGoodVo.province !== orderGoodVo.province ||
            firstOrderGoodVo.city !== orderGoodVo.city ||
            firstOrderGoodVo.area !== orderGoodVo.area
          ) {
            isAllGoodUserSame = false
          }
        })
        isDisabledUserInput.value = isAllGoodUserSame

        addrs.value = {
          province: firstOrderGoodVo.province,
          city: firstOrderGoodVo.city,
          area: firstOrderGoodVo.area,
          town: firstOrderGoodVo.town,
        }

        if (firstOrderGoodVo.userId) {
          basicData.value.userId = firstOrderGoodVo.userId
        }

        if (firstOrderGoodVo.name) {
          basicData.value.name = firstOrderGoodVo.name
        }

        if (firstOrderGoodVo.phone) {
          basicData.value.phone = firstOrderGoodVo.phone
        }

        if (firstOrderGoodVo.address) {
          basicData.value.address = firstOrderGoodVo.address
        }
      }
    })
    // if (
    //   (repeatOrderObj.value.enableGoodsModel || repeatOrderObj.value.enableGoodsName) &&
    //   repeatOrderObj.value.enableSNCode
    // ) {
    //   repeatSearch.value.goodsIds = goodsIds
    //   repeatSearch.value.codeIds = codeIds
    //   if (repeatSearch.value.goodsIds.length > 0) is_RepeatOrderArr.value.push(1)
    //   is_RepeatOrderArr.value.push(2)
    //   is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
    //   if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort()))
    //     getRepeatOrderFun(repeatSearch.value, true)
    // } else if (repeatOrderObj.value.enableGoodsModel || repeatOrderObj.value.enableGoodsName) {
    //   repeatSearch.value.goodsIds = goodsIds
    //   if (repeatSearch.value.goodsIds.length > 0) is_RepeatOrderArr.value.push(1)
    //   is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
    //   if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort()))
    //     getRepeatOrderFun(repeatSearch.value, true)
    // } else if (repeatOrderObj.value.enableSNCode) {
    //   repeatSearch.value.codeIds = codeIds
    //   is_RepeatOrderArr.value.push(2)
    //   is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
    //   if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort()))
    //     getRepeatOrderFun(repeatSearch.value, true)
    // } else {
    //   repeatSearch.value.codeIds = []
    //   repeatSearch.value.goodsIds = []
    //   is_RepeatOrderArr.value = is_RepeatOrderArr.value.filter((o) => !(o == 1 || o == 2))
    // }
  }

  const orderSaveFun = async () => {
    const useAddr = singleAddressRef.value.getSelectAddr()
    if (!useAddr.province) {
      HMessageBox.error(infoTip.order.create.noContactAddress)
      return
    }
    const orderGoods = goodInfoInstance.value.getGoods()
    if (orderGoods.length <= 0) {
      HMessageBox.error(infoTip.order.create.noGood)
      return
    }
    let data = {
      content: basicData.value.content, //故障描述
      createTime: now.value, //下单时间
      delImageIds: [], //删除的工单附件ID集合
      delOrderGoodsIds: [], //删除的工单产品对象ID集合
      id: null, //工单ID，新增不必传，修改必传
      imageVos: [],
      moduleId: basicData.value.moduleId, //工单模块ID
      networkId: network.value, //网点表ID
      orderGoodsTypes: orderGoods,
      factoryId: basicData.value.factoryId || '0', // 品牌商家ID
      orderUser: {
        name: basicData.value.name, //公司姓名
        otherPhone: '', //其他电话
        phone: basicData.value.phone, //公司手机号
        userId: basicData.value.userId, //公司ID
        province: useAddr.province, //地址-省
        city: useAddr.city, //地址-市
        area: useAddr.area, //地址-县/区
        town: useAddr.town, //地址-镇
        address: basicData.value.address, //公司详细地址
        sendForRepairUsername: basicData.value.repairCompany, //送修人
        sendForRepairPhone: basicData.value.repairCompanyPhone, //送修人手机
        repairCompany: basicData.value.repairCompany, // 报修公司名称
        repairCompanyId: basicData.value.repairCompanyId, // 报修公司ID
        repairCompanyPhone: basicData.value.repairCompanyPhone, // 报修公司联系方式
        storeName: basicData.value.storeName,
        businessPhone: basicData.value.businessPhone,
      },
      overinsured: basicData.value.overinsured, //质保状态，是否保外：false-保内，true-保外
      source: basicData.value.source, //工单来源
      threeTypeId: null, //工单模块分类ID3
      threeWayId: null, //工单模块方式ID3
      twoTypeId: null, //工单模块分类ID2
      twoWayId: null, //工单模块方式ID2
      oneTypeId: null, //工单模块分类ID1
      oneWayId: null, //工单模块方式ID1
      workLevelId: grade.value, //工单级别ID
      workFieldVal: [], //工单自定义字段值对象,
      faultRelationVos:
        basicData.value.departmentId === departmentFixedData.business
          ? basicData.value.faultRelationVos.map((item) => {
              // 如果id的位数小于5位就说明这个选项是动态新增的，需要将id重置为0
              if (item.faultId.length <= 5) {
                return {
                  faultId: '0',
                  fault: item.fault,
                }
              }
              return item
            })
          : [],
      faultReason: basicData.value.faultReason,
      solution: basicData.value.solution,
      faultTypeRelationVos: basicData.value.faultTypeRelationVos,
      workImages: [],
      workGoodsType: basicData.value.departmentId === departmentFixedData.family ? 2 : 1,
      saleChannel: basicData.value.saleChannel,
      buyPlatformOrderNo: basicData.value.buyPlatformOrderNo,
      accountability:
        basicData.value.departmentId === departmentFixedData.business
          ? basicData.value.accountability
          : '',
      serviceType:
        basicData.value.departmentId === departmentFixedData.business
          ? basicData.value.serviceType
          : '',
      serviceMode:
        basicData.value.departmentId === departmentFixedData.business
          ? basicData.value.serviceMode
          : '',
      remark: basicData.value.remark,
      orderReservationStartTime: `${basicData.value.orderReservationDate} ${basicData.value.orderReservationstartTime}`,
      orderReservationEndTime: `${basicData.value.orderReservationDate} ${basicData.value.orderReservationEndTime}`,
      departmentId: basicData.value.departmentId,
      empId: basicData.value.empId,
      workSourceId: basicData.value.workSourceId,
    }
    // if (data.faultReason.length && !faultReasonOptions.value.length) {
    //   data.faultReason = [{ id: 0, content: data.faultReason }]
    // }

    // if (data.solution.length && !solveOptions.value.length) {
    //   data.solution = [{ id: 0, content: data.solution }]
    // }
    // 工单模块分类
    if (type.value?.length > 0) {
      type.value.map((o, i) => {
        if (i == 0) {
          data.oneTypeId = o
        }
        if (i == 1) {
          data.twoWayId = o
        }
        if (i == 2) {
          data.threeTypeId = o
        }
      })
    }
    // 工单模块方式
    if (method.value?.length > 0) {
      method.value.map((o, i) => {
        if (i == 0) {
          data.oneWayId = o
        }
        if (i == 1) {
          data.twoWayId = o
        }
        if (i == 2) {
          data.threeWayId = o
        }
      })
    }
    submitLoading.value = true
    // 判断是否有图片
    if (fileList.value?.length > 0) {
      let imageList = fileList.value.map((o) => {
        return o.file
      })
      // 上传图片
      data.imageVos = []
      const orderAnnexUploadRes = await orderAnnexUpload(imageList)
      if (orderAnnexUploadRes.data.success) {
        for (let i = 0; i < orderAnnexUploadRes.data.data.rows.length; i++) {
          data.imageVos.push({ id: null, image: orderAnnexUploadRes.data.data.rows[i], type: 1 })
        }
      } else {
        HMessageBox.error(orderAnnexUploadRes.data.message)
      }

      const imgUrls = fileList.value.map((img) => img.image.includes('http'))
      if (imgUrls.length > 0) {
        imgUrls.forEach((img) => {
          data.imageVos.push({ id: null, image: img, type: 1 })
        })
      }
    }

    if (goodCodeImgFile.value.file) {
      const res = await orderAnnexUpload([goodCodeImgFile.value.file])
      if (res.data.code === 20000) {
        data.imageVos.push({
          id: null,
          type: 3,
          image: res.data.data.rows[0],
        })
      }
    }

    if (goodFaultImgFile.value.file) {
      const res = await orderAnnexUpload([goodFaultImgFile.value.file])
      if (res.data.code === 20000) {
        data.imageVos.push({
          id: null,
          type: 4,
          image: res.data.data.rows[0],
        })
      }
    }

    // 自定义字段文件上传
    // const customFieldFileList = customFieldList.value.filter((field) =>
    //   [5, 6, 7].includes(field.type),
    // )
    // for (let index = 0; index < customFieldFileList.length; index++) {
    //   let optionVos: Array<{ id: string; optValue: string }> = []
    //   if (customFieldFileList[index].type === 7) {
    //     const orderVideoUploadRes = await orderVideoUpload(
    //       customFieldFileList[index].fileList.map((file) => file.file),
    //     )
    //     if (orderVideoUploadRes.data.code === 20000) {
    //       optionVos = orderVideoUploadRes.data.data.rows.map((item) => {
    //         return {
    //           id: '',
    //           optValue: item,
    //         }
    //       })
    //     } else {
    //       HMessageBox.error(orderVideoUploadRes.data.message)
    //     }
    //   }

    //   if (customFieldFileList[index].type === 5 || customFieldFileList[index].type === 6) {
    //     const orderAnnexUploadRes = await orderAnnexUpload(
    //       customFieldFileList[index].fileList.map((file) => file.file),
    //     )
    //     if (orderAnnexUploadRes.data.code === 20000) {
    //       optionVos = orderAnnexUploadRes.data.data.rows.map((item) => {
    //         return {
    //           id: '',
    //           optValue: item,
    //         }
    //       })
    //     } else {
    //       HMessageBox.error(orderAnnexUploadRes.data.message)
    //     }
    //   }

    //   data.workFieldVal.push({
    //     id: '',
    //     moduleFieldId: customFieldFileList[index].moduleFieldId,
    //     name: customFieldFileList[index].name,
    //     type: customFieldFileList[index].type,
    //     workFieldId: customFieldFileList[index].workFieldId,
    //     optionVos,
    //   })
    // }

    // 自定义字段（文本、多行文本、单选、评分、日期、日期时间）
    // customFieldList.value
    //   .filter((field) => [1, 2, 3, 8, 9, 10].includes(field.type))
    //   .forEach((field) => {
    //     data.workFieldVal.push({
    //       id: '',
    //       moduleFieldId: field.moduleFieldId,
    //       name: field.name,
    //       type: field.type,
    //       workFieldId: field.workFieldId,
    //       optionVos: [
    //         {
    //           id: '',
    //           optValue: field.val,
    //         },
    //       ],
    //     })
    //   })

    // 自定义字段（多选）
    // customFieldList.value
    //   .filter((field) => field.type === 4)
    //   .forEach((field) => {
    //     data.workFieldVal.push({
    //       id: '',
    //       moduleFieldId: field.moduleFieldId,
    //       name: field.name,
    //       type: field.type,
    //       workFieldId: field.workFieldId,
    //       optionVos: field.valList.map((value) => {
    //         return {
    //           id: '',
    //           optValue: value,
    //         }
    //       }),
    //     })
    //   })

    await addSave(data).then((res) => {
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'error',
        duration: 5000,
        showClose: true,
        plain: true,
      })
      if (res.data.code === 20000) {
        repeatSearch.value = {
          codeIds: [], //产品条码
          goodsIds: [], //产品IDs
          moduleId: '', //模块ID
          userPhone: '', //公司手机号
          username: '', //公司姓名
        }
        is_RepeatOrderArr.value = []
        useTagsViewStore().delView(router.currentRoute.value.path)
        refresh()
        goodInfoInstance.value.clear()
        if (res.data.data.id) {
          router.push(`/order/odetail/${res.data.data.id}`)
        } else {
          router.push({ path: '/order/list' })
        }
      }
    })
    submitLoading.value = false
  }

  /**
   * 产品故障图上传事件
   * @param {UploadFile} file - 文件对象
   */
  // const handleUploadGoodFaultImg = (file: UploadFile) => {
  //   goodFaultImgFile.value.file = file.raw
  //   goodFaultImgFile.value.url = URL.createObjectURL(file.raw)
  // }

  /**
   * 产品条码图上传事件
   * @param {UploadFile} file - 文件对象
   */
  // const handleUploadGoodCodeImg = (file: UploadFile) => {
  //   goodCodeImgFile.value.file = file.raw
  //   goodCodeImgFile.value.url = URL.createObjectURL(file.raw)
  // }

  /**
   * 提交工单
   */
  const submitOrder = async () => {
    if (isSelectedUserJoinBlackList.value) {
      HMessageBox.error(infoTip.order.create.user_joined_back_list)
      return
    }

    if (!customerInfoFormInstance.value) {
      return
    }

    try {
      await customerInfoFormInstance.value.validate()
    } catch (error) {
      customerInfoDiv.value.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' })
      return false
    }

    if (!basicInfoFormInstance.value) {
      return
    }

    try {
      await basicInfoFormInstance.value.validate()
    } catch (error) {
      basicInfoDiv.value.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' })
      return false
    }

    if (!goodInfoInstance.value) {
      return
    }

    const orderGoods = goodInfoInstance.value.getGoods()
    if (orderGoods.length <= 0) {
      HMessageBox.error(infoTip.order.create.noGood)
      goodInfoDiv.value.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' })
      return
    }

    // if (customFieldList.value.length > 0) {
    //   if (!customFieldFormInstance.value || customFieldFormInstance.value.length <= 0) {
    //     return
    //   }
    // }

    // const { userId, name } = basicData.value
    // if (userId && name) {
    //   const userCreditLimitErrMsg = await judgeUserCreditLimit(userId, name)
    //   if (userCreditLimitErrMsg) {
    //     HMessageBox.error(userCreditLimitErrMsg)
    //     return
    //   }
    // }

    // if (customFieldList.value.length > 0) {
    //   try {
    //     for (let i = 0; i < customFieldFormInstance.value.length; i++) {
    //       await customFieldFormInstance.value[i].validate()
    //     }
    //   } catch (error) {
    //     customInfoDiv.value.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' })
    //     return false
    //   }
    // }

    // await getRepeatOrderSetFun()
    // is_RepeatOrderArr.value = is_RepeatOrderArr.value.filter((o) => !(o == 3 || o == 4))
    // if (repeatOrderObj.value.enableUserPhone && repeatOrderObj.value.enableUserName) {
    //   repeatSearch.value.userPhone = basicData.value.phone
    //   repeatSearch.value.username = basicData.value.name
    //   if (repeatSearch.value.userPhone) is_RepeatOrderArr.value.push(4)
    //   if (repeatSearch.value.username) is_RepeatOrderArr.value.push(3)
    // } else if (repeatOrderObj.value.enableUserName) {
    //   repeatSearch.value.username = basicData.value.name
    //   if (repeatSearch.value.username) is_RepeatOrderArr.value.push(3)
    // } else if (repeatOrderObj.value.enableUserPhone) {
    //   repeatSearch.value.userPhone = basicData.value.phone
    //   if (repeatSearch.value.userPhone) is_RepeatOrderArr.value.push(4)
    // }
    // is_RepeatOrderArr.value = is_RepeatOrderArr.value.filter((o) => o !== 5)
    // if (repeatOrderObj.value.enableOrderModule) {
    //   repeatSearch.value.moduleId = basicData.value.moduleId
    //   if (repeatSearch.value.moduleId) is_RepeatOrderArr.value.push(5)
    // }

    // let codeIds = []
    // let goodsIds = []
    // is_RepeatOrderArr.value = is_RepeatOrderArr.value.filter((o) => !(o == 1 || o == 2))
    // orderGoods.map((o) => {
    //   o.orderGoodsVos.map((i) => {
    //     if (i.codeIds.length > 0) {
    //       codeIds.push(...i.codeIds)
    //     }
    //     if (i.goodsId) {
    //       goodsIds.push(i.goodsId)
    //     }
    //   })
    // })
    // if (
    //   (repeatOrderObj.value.enableGoodsModel || repeatOrderObj.value.enableGoodsName) &&
    //   repeatOrderObj.value.enableSNCode
    // ) {
    //   repeatSearch.value.goodsIds = goodsIds
    //   repeatSearch.value.codeIds = codeIds
    //   if (repeatSearch.value.goodsIds.length > 0) is_RepeatOrderArr.value.push(1)
    //   is_RepeatOrderArr.value.push(2)
    // } else if (repeatOrderObj.value.enableGoodsModel || repeatOrderObj.value.enableGoodsName) {
    //   repeatSearch.value.goodsIds = goodsIds
    //   if (repeatSearch.value.goodsIds.length > 0) is_RepeatOrderArr.value.push(1)
    // } else if (repeatOrderObj.value.enableSNCode) {
    //   repeatSearch.value.codeIds = codeIds
    //   is_RepeatOrderArr.value.push(2)
    // } else {
    //   repeatSearch.value.codeIds = []
    //   repeatSearch.value.goodsIds = []
    //   is_RepeatOrderArr.value = is_RepeatOrderArr.value.filter((o) => !(o == 1 || o == 2))
    // }
    // is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
    // if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort())) {
    //   let is_repeat = await getRepeatOrderFun(repeatSearch.value)
    //   if (is_repeat.code) {
    //     if (is_repeat.val) {
    //       ElMessageBox.confirm('存在重复工单，是否继续报单？', '提示', {
    //         type: 'warning',
    //         icon: markRaw(WarningFilled),
    //         confirmButtonText: '继续',
    //         cancelButtonText: '取消',
    //       })
    //         .then(() => {
    //           orderSaveFun()
    //         })
    //         .catch(() => {
    //           return
    //         })
    //       return
    //     } else {
    //       ElMessageBox.confirm('存在重复工单，不允许报单!', '提示', {
    //         type: 'error',
    //         icon: markRaw(CircleCloseFilled),
    //         showCancelButton: false,
    //       })
    //       return
    //     }
    //   }
    //   orderSaveFun()
    // } else {
    orderSaveFun()
    // }
  }

  /**
   * 工单图片上传失败错误信息提示
   * @param {'type' | 'size' | 'count'} type - 提示类型
   */
  const orderPictureUploadFailIntoTip = _.debounce((type: 'type' | 'size' | 'count') => {
    switch (type) {
      case 'type':
        HMessageBox.error(infoTip.order.create.order_picture_upload_type_err)
        break
      case 'size':
        HMessageBox.error(infoTip.order.create.order_picture_upload_size_err)
        break
      case 'count':
        HMessageBox.error(infoTip.order.create.order_picture_upload_count_err)
        break
    }
  }, 100)

  /**
   * 上传工单图片事件
   * @param {UploadFile} uploadFile - 文件对象
   */
  const handleUploadOrderPicture = (uploadFile: UploadFile) => {
    if (!uploadFile.raw.type.includes('image')) {
      orderPictureUploadFailIntoTip('type')
      return
    }

    if (uploadFile.raw.size / 1024 / 1024 > 50) {
      orderPictureUploadFailIntoTip('size')
      return
    }

    if (fileList.value.length >= 3) {
      orderPictureUploadFailIntoTip('count')
      return
    }
    let { uid, name } = uploadFile.raw
    let tmp = {
      uid,
      name,
      image: window.URL.createObjectURL(uploadFile.raw),
      file: uploadFile.raw,
      upDatatime: new Date(Date.now()).toISOString().split('T')[0],
    }
    fileList.value.push(tmp)
  }

  /**
   * 删除图片
   * @param {Number} index - 工单图片索引
   */
  const handleDelOrderPicture = (index: number) => {
    fileList.value.splice(index, 1)
    fileList.value = fileList.value.filter((o, i) => i != index)
  }

  //工单分类下拉数据
  const getworkModuleTypePageSelect = async (val, id) => {
    if (!id) return
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    const res = await workModuleTypePageSelect(data, id)
    types.value = res.data.data.rows
  }

  //工单分类下拉远程搜索
  // const inputChangeType = async (val) => {
  //   if (basicData.value.moduleId) {
  //     await getworkModuleTypePageSelect(val, basicData.value.moduleId)
  //   }
  // }

  // 处理方式下拉远程搜索
  // const inputChangeMethod = async (val) => {
  //   if (val && basicData.value.moduleId) {
  //     await getworkModuleWayPageSelect(val, basicData.value.moduleId)
  //   }
  // }

  // 获取工单类型下拉选项请求参数
  const getOrderTypeOptionsParam = ref<{
    limit: number
    name: string
    page: number
    ascriptionType?: 1 | 2
    id: string
    departmentId: string
  }>({
    limit: 0,
    page: 0,
    name: '',
    ascriptionType: 1,
    departmentId: '',
    id: '',
  })

  /**
   * 获取工单类型下拉选项
   */
  const handleGetOrderTypeOptions = _.throttle((query: string) => {
    if (query === getOrderTypeOptionsParam.value.name) {
      return false
    }
    getOrderTypeOptionsParam.value.name = query
    getOrderTypeOptionsFn()
  }, 500)

  /**
   * 获取工单类型下拉选项方法
   */
  const getOrderTypeOptionsFn = async () => {
    loading.value = true
    getOrderTypeOptionsParam.value.departmentId = basicData.value.departmentId
    const res = await workModulePageSelect(getOrderTypeOptionsParam.value)
    if (res.data.success) {
      modules.value = res.data.data.rows
    }
    loading.value = false
  }

  /**
   * 获取自定义字段
   * @param {String} moduleId 工单模块id
   */
  const getCustomField = async (moduleId: string) => {
    if (!moduleId) {
      return
    }

    const res = await getModuleField(moduleId)
    submitFormShow.value = res.data.data.row.length > 0
    customFieldList.value = res.data.data.row.map((field, index) => {
      return {
        contents: field.contents,
        moduleFieldId: field.moduleFieldId,
        name: field.name,
        required: field.required,
        status: field.status,
        tip: field.tip,
        type: field.type,
        uploadQty: field.uploadQty,
        uploadSize: field.uploadSize,
        workFieldId: field.workFieldId,
        formCustomFieldIndex: index,
        val: '',
        valList: [],
        fileList: [],
      }
    })
  }

  /**
   * 切换工单类型
   * @param {Object} val - 工单模块
   */
  const handleChangeModule = (val: OrderType) => {
    type.value = val.type
    basicData.value.overinsured = val.overinsured
    // if (val.autoDispatchClient) {
    //   customer.value = 0
    // }
    // if (val.autoDispatchNetwork) {
    //   network.value = ''
    // }
    getworkModuleWayPageSelect('', val.id)
    getworkModuleTypePageSelect('', val.id)
    getCustomField(val.id)
    nextTick(() => {
      formRef.value?.resetFields()
    })
  }

  /**
   * 获取服务级别下拉选项
   */
  // const getworkLevelPageSelect = _.throttle((val) => {
  //   let data = {
  //     limit: 0,
  //     name: val,
  //     page: 0,
  //   }
  //   loading.value = true
  //   workLevelPageSelect(data).then((res) => {
  //     if (res.data.success) {
  //       grades.value = res.data.data.rows
  //     }
  //     loading.value = false
  //   })
  // }, 500)

  /**
   * 工单客服组下拉列表查询
   * @param {string} keyword - 搜索关键字
   */
  const getCustomerOptions = _.debounce((keyword: string) => {
    getCustomerOptionsLoading.value = true
    empPageSelecct({
      limit: 0,
      name: keyword,
      page: 0,
    })
      .then((res) => {
        if (res.data.code === 20000) {
          customerOptions.value = res.data.data.rows
        }
      })
      .finally(() => {
        getCustomerOptionsLoading.value = false
      })
  }, 500)

  /**
   * 获取网点下拉选项
   */
  const getNetworkPageSelectList = _.throttle((val: string) => {
    let data = {
      limit: 100,
      name: val,
      page: 1,
    }
    loading.value = true
    getNetworkPageSelect(data).then((res) => {
      if (res.data.success) {
        networks.value = res.data.data.rows
      }
      loading.value = false
    })
  }, 500)

  // 保存新公司
  const onSaveCreateUser = (formEl: FormInstance) => {
    formEl.validate((valid) => {
      if (!valid) {
        return
      }
      onClearUser()
      basicData.value.userId = '0'
      basicData.value.accountNo = createUserForm.phone
      basicData.value.name = createUserForm.name
      basicData.value.phone = createUserForm.phone
      createUserDialogVisit.value = false
    })
  }

  // const getUserOptionsLoading = ref(false)
  // const userOptions = ref<Array<CustomerOption>>([])
  const customerSelectPopoverVisible = ref(false)

  // 反馈人选择弹出框显示状态
  const feedbackPersonSelectPopoverVisible = ref(false)

  /**
   * 客户名称输入事件
   * @param {string} keyword - 搜索关键字
   */
  const handleCustomerNameInput = _.debounce((keyword: string) => {
    customerSelectPopoverVisible.value = true
    if (keyword.trim()) {
      getUserOptionListParam.value.name = keyword.trim()
      getUserOptionList()
    }
  }, 600)

  /**
   * 反馈人输入事件
   * @param {string} keyword - 搜索关键字
   */
  const handleFeedbackPersonInput = _.debounce((keyword: string) => {
    if (keyword.trim()) {
      feedbackPersonSelectPopoverVisible.value = true
      getSendRepairUserOptionListParam.value.name = keyword
      getSendRepairUserOptionList()
    }
  }, 600)

  // const getUserOptions = async () => {
  //   getUserOptionsLoading.value = true
  //   const res = await getUserSelect({
  //     limit: 0,
  //     name: basicData.value.name,
  //     page: 0,
  //   })
  //   getUserOptionsLoading.value = false
  //   if (res.data.code === 20000) {
  //     userOptions.value = res.data.data.rows
  //   }
  // }

  /**
   * 根据公司的信用额度来判断是否允许创建工单
   * @param {string} userId - 公司id
   * @param {string} userName - 公司名
   */
  // const judgeUserCreditLimit = async (userId: string, userName: string) => {
  //   await getCreditLimit(userId)
  //   const { allowCreateOrderWithSureEndOrder, creditLimitType, unpaidPrice, limitType } =
  //     userCreditLimitByOrderTip.value
  //   if (!allowCreateOrderWithSureEndOrder) {
  //     if (creditLimitType === 2) {
  //       return `公司（${userName}）还有${unpaidPrice.toFixed(2)}元的账款未结清，不允许创建工单`
  //     }

  //     if (creditLimitType === 3) {
  //       if (limitType === 2) {
  //         return `公司（${userName}）的信用额度已超出限制，不允许创建工单`
  //       }

  //       if (limitType === 3) {
  //         return `公司（${userName}）还有${unpaidPrice.toFixed(
  //           2,
  //         )}元的账款已逾期未结清，不允许创建工单`
  //       }

  //       return ''
  //     }

  //     return ''
  //   }
  //   return ''
  // }

  /**
   * 客户、反馈人选择事件
   * @param {string} user - 选择的客户、反馈人
   * @param {1|2} type - 选择类型，1-客户，2-反馈人
   */
  const handleChangeUser = async (user: UserMainContactPersonOption, type?: number) => {
    customerSelectPopoverVisible.value = false
    feedbackPersonSelectPopoverVisible.value = false

    if (user) {
      isSelectedUserJoinBlackList.value = user.blacklist
      if (user.blacklist) {
        HMessageBox.error(infoTip.order.create.user_joined_back_list)
      }

      nextTick(() => {
        // 商用：反馈人，家用：联系人
        if (type == 2) {
          addrs.value = {
            province: user.province,
            city: user.city,
            area: user.area,
            town: user.town,
          }
          if (user.address) {
            basicData.value.address = user.address
          }
          if (user.phone) {
            basicData.value.repairCompanyPhone = user.phone
          }
        }

        // 商用：客户，家用：店铺/渠道
        if (type == 1 && basicData.value.departmentId === departmentFixedData.business) {
          addrs.value = {
            province: user.province,
            city: user.city,
            area: user.area,
            town: user.town,
          }
          if (user.address) {
            basicData.value.address = user.address
          }
        }
      })
      if (type == 1) {
        if (user.userId) {
          basicData.value.userId = user.userId
        }

        if (user.name) {
          basicData.value.name = user.name
        }

        if (user.phone) {
          basicData.value.phone = user.phone
        }

        if (user.phone) {
          basicData.value.businessPhone = user.phone
        }
      }

      if (type == 2) {
        if (user.name) {
          basicData.value.repairCompany = user.name
        }
      }

      // const errMsg = await judgeUserCreditLimit(user.userId, user.username)
      // if (errMsg) {
      //   HMessageBox.error(errMsg)
      // }
    }
  }

  const onClearUserInfo = () => {
    if (basicData.value.workGoodsType == 2) {
      nextTick(() => {
        addrs.value = {
          province: '',
          city: '',
          area: '',
          town: '',
        }
      })
      basicData.value.address = ''
      if (singleAddressRef.value) {
        singleAddressRef.value.clearSelectAddr()
      }
    }
    basicData.value.userId = ''
    basicData.value.name = ''
    basicData.value.phone = ''

    customerSelectPopoverVisible.value = false
  }

  /**
   * 反馈人清除事件
   */
  const onClearUserInfo2 = () => {
    if (basicData.value.workGoodsType == 1) {
      nextTick(() => {
        addrs.value = {
          province: '',
          city: '',
          area: '',
          town: '',
        }
      })
      basicData.value.address = ''
      if (singleAddressRef.value) {
        singleAddressRef.value.clearSelectAddr()
      }
    }
    basicData.value.repairCompanyPhone = ''
    customerSelectPopoverVisible.value = false
  }

  // 清除公司账号
  const onClearUser = () => {
    basicData.value.name = ''
    basicData.value.userId = ''
    basicData.value.accountNo = ''
    singleAddressRef.value.clearSelectAddr()
  }

  //  通过模块id 获取处理方式
  const getworkModuleWayPageSelect = async (val, id) => {
    if (!id) return
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    const res = await workModuleWayPageSelect(data, id)
    methodss.value = res.data.data.rows
  }
  // 工单分类下拉框出现/隐藏时触发
  // const changeType = async () => {
  //   showType.value = !showType.value
  //   if (!showType.value) {
  //     if (!(type.value instanceof Array)) {
  //       await getworkModuleTypePageSelect('', basicData.value.moduleId)
  //     }
  //   }
  // }
  // 处里方式下拉框出现/隐藏时触发
  // const changeMmethod = async () => {
  //   showType.value = !showType.value
  //   if (!showType.value) {
  //     if (!(method.value instanceof Array)) {
  //       await getworkModuleWayPageSelect('', basicData.value.moduleId)
  //     }
  //   }
  // }

  // 用户的整段信息，包含姓名、手机号、地址
  const allUserInfo = ref('')

  const getLoginedNetworkIdLoading = ref(false)
  /**
   * 获取登录的账号所在的网点id
   */
  const getLoginedNetworkId = async () => {
    try {
      getLoginedNetworkIdLoading.value = true
      const res = await getLoginAccountNetworkId()
      getLoginedNetworkIdLoading.value = false
      network.value = res.data.data.row
      loginedAccountNetwork.value = res.data.data.row
    } catch (error) {
      getLoginedNetworkIdLoading.value = false
    }
  }

  /**
   * 设置默认的产品类型
   */
  const setDefaultProductType = () => {
    const role = userStore.$state.role[0]
    if (role) {
      const departmentIds = (role.department || []).map((item) => item.id)
      if (departmentIds[0]) {
        basicData.value.departmentId = departmentIds[0]
      }
    }
  }

  // 获取当前账号的商用-家用类型
  const unDep = ref(true) // 是否没有部门，有部门就禁用不能选择
  const getOrganTypeInfoLoading = ref(false)
  const getOrganTypeInfo = () => {
    getOrganTypeInfoLoading.value = true
    getOrganType()
      .then((res) => {
        if (res.data.code === 20000) {
          const organType = res.data.data.organType
          unDep.value = organType ? false : true
          getOrderTypeOptionsParam.value.ascriptionType = organType || ''
          basicData.value.workGoodsType = organType || ''
          setTimeout(() => {
            if (customerInfoFormInstance.value) {
              customerInfoFormInstance.value.clearValidate()
            }
            if (basicInfoFormInstance.value) {
              basicInfoFormInstance.value.clearValidate()
            }
          }, 0)
          getOrderTypeOptionsFn()
        }
      })
      .finally(() => {
        getOrganTypeInfoLoading.value = false
      })
  }

  // 切换类型
  const changeWorkGoodsType = () => {
    basicData.value.moduleId = ''
    getOrderTypeOptionsParam.value.ascriptionType = basicData.value.workGoodsType
    getOrderTypeOptionsFn()
  }

  const handleBusinessPhoneInput = (value: string) => {
    basicData.value.businessPhone = value.substring(0, 11)
    basicData.value.businessPhone = value.replace(/[^0-9]/g, '')
  }

  const handleFeedbackPhoneInput = (value: string) => {
    basicData.value.repairCompanyPhone = value.substring(0, 11)
    basicData.value.repairCompanyPhone = value.replace(/[^0-9]/g, '')
  }

  const pasteOrderInfoFromClipboard = async () => {
    // const orderInfo = await navigator.clipboard.readText()
    // const orderInfoCopyRow = JSON.parse(orderInfo)
    // if (!orderInfoCopyRow) {
    //   return
    // }
    if (!orderDetailToPaste || orderGoodListToPaste.length <= 0) {
      return
    }

    basicData.value.departmentId = orderDetailToPaste.departmentId
    await getOrderTypeOptionsFn()
    basicData.value.name = orderDetailToPaste.name
    basicData.value.businessPhone = orderDetailToPaste.businessPhone
    basicData.value.userId = orderDetailToPaste.userId
    basicData.value.repairCompany = orderDetailToPaste.sendForRepairUsername
    basicData.value.repairCompanyPhone = orderDetailToPaste.sendForRepairPhone
    basicData.value.storeName = orderDetailToPaste.storeName
    addrs.value = {
      province: orderDetailToPaste.province,
      city: orderDetailToPaste.city,
      area: orderDetailToPaste.area,
      town: orderDetailToPaste.town,
    }
    basicData.value.address = orderDetailToPaste.address
    basicData.value.saleChannel = orderDetailToPaste.saleChannel
    basicData.value.moduleId = orderDetailToPaste.moduleId
    basicData.value.buyPlatformOrderNo = orderDetailToPaste.buyPlatformOrderNo
    basicData.value.serviceType = orderDetailToPaste.serviceType
    basicData.value.serviceMode = orderDetailToPaste.serviceMode
    basicData.value.content = orderDetailToPaste.content
    basicData.value.faultTypeRelationVos = (orderDetailToPaste.faultType || []).map((item) => {
      return {
        oneFaultTypeId: item.oneFaultTypeId,
        threeFaultTypeId: item.threeFaultTypeId,
        twoFaultTypeId: item.twoFaultTypeId,
      }
    })
    if (orderDetailToPaste.empId && orderDetailToPaste.empId !== '0') {
      basicData.value.empId = orderDetailToPaste.empId
    }
    basicData.value.remark = orderDetailToPaste.remark
    basicData.value.accountability = orderDetailToPaste.accountability
    network.value = orderDetailToPaste.networkId === '0' ? '' : orderDetailToPaste.networkId
    basicData.value.overinsured = orderDetailToPaste.overinsured
    fileList.value = orderDetailToPaste.orderImages.map((image) => {
      return {
        uuid: '',
        name: (image.split('/').at(-1) || '').split('.')[0],
        image,
        file: null,
        upDatatime: '',
      }
    })

    if (!goodInfoInstance.value) {
      return
    }

    orderGoodListToPaste.forEach((good: OrderDetailAPIResponse.GoodListItem) => {
      const addRow: TableDataGoodInfoOrderCreate = {
        code: '',
        goodsName: good.goodsName,
        goodsSpecName: good.goodsSpec,
        goodsBrand: good.goodsBrand,
        qty: good.qty,
        img: '',
        buyTime: good.buyTime,
        name: good.userName,
        phone: good.userPhone,
        province: good.province,
        city: good.city,
        area: good.area,
        town: good.town,
        address: good.address,
        isEmptyLine: false,
        type: 2,
        goodId: good.goodsId,
        goodSpecId: good.goodsSpecId,
        codeId: '',
        goodsSpecCode: good.goodsCode,
        warrantyDay: 0,
        warrantyStartTime: good.buyTime,
        warrantyEndTime: good.endTime,
        userId: '',
        saleModels: '',
        registerCode: '',
      }
      if (good.codes && good.codes.length > 0) {
        good.codes.forEach((code) => {
          Object.assign(addRow, {
            code: code.securityCode,
            type: good.userId ? 1 : 2,
            codeId: code.id,
            warrantyDay: code.warrantyDay,
            userId: good.userId,
            registerCode: code.registerCode || '',
          })
          if (goodInfoInstance.value) {
            goodInfoInstance.value.addGood(addRow)
          }
        })
      } else {
        if (addRow.warrantyStartTime && addRow.warrantyEndTime) {
          const startTimestamp = new Date(addRow.warrantyStartTime).getTime()
          const endTimestamp = new Date(addRow.warrantyEndTime).getTime()
          addRow.warrantyDay = Math.ceil((endTimestamp - startTimestamp) / (1000 * 3600 * 24))
        }
        if (goodInfoInstance.value) {
          goodInfoInstance.value.addGood(addRow)
        }
      }
    })

    clearCopyInfo()
  }

  // 监听处里方式下拉选择
  watch(
    () => method.value,
    (n) => {
      if (!n) {
        getworkModuleWayPageSelect('', basicData.value.moduleId)
      }
    },
  )

  // 监听工单分类下拉选择
  watch(
    () => type.value,
    (n) => {
      if (!n) {
        getworkModuleTypePageSelect('', basicData.value.moduleId)
      }
    },
  )

  // 请求获取下拉数据
  onMounted(async () => {
    getWorkSourceList().then(() => {
      if (workSourceList.value[0]) {
        basicData.value.workSourceId = workSourceList.value[0].id
      }
    })
    getFaultTypeOptions().then(() => {
      if (faultTypeOptions.value[0]) {
        basicData.value.faultTypeRelationVos = [
          {
            oneFaultTypeId: faultTypeOptions.value[0].id,
            threeFaultTypeId: '',
            twoFaultTypeId: '',
          },
        ]
      }
    })
    // getUserOptions()
    getSendRepairUserOptionList()
    getUserOptionList()
    getOrganTypeInfo()
    await getDepartmentOptions()
    setDefaultProductType()
    getOrderTypeOptionsFn().then(() => {
      if (modules.value[0]) {
        basicData.value.moduleId = modules.value[0].id
      }
    })
    if (userStore.isCurrentRoleNetwork) {
      getLoginedNetworkId()
    }
    let data = {
      limit: 0,
      name: '',
      page: 0,
    }
    loading.value = true
    workLevelPageSelect(data)
      .then((res) => {
        if (res.data.success) {
          grades.value = res.data.data.rows
          if (grades.value) {
            grades.value.filter((o) => {
              if (o.select) {
                grade.value = o.id
              }
            })
          }
        }
      })
      .finally(() => {
        loading.value = false
      })
    getCustomerOptions('')
    getNetworkPageSelectList('')
    // 设置当前时间
    now.value =
      new Date(Date.now()).toISOString().split('T')[0] +
      ' ' +
      new Date(Date.now()).toTimeString().split(' ')[0]
    basicData.value.empId = userStore.$state.userInfo.id

    nextTick(() => {
      if (goodInfoInstance.value) {
        goodInfoInstance.value.clear()
      }
    })

    pasteOrderInfoFromClipboard()
  })

  onUnmounted(() => {
    file.value = 'about:blank'
  })
</script>

<style lang="scss" scoped>
  .select-header {
    display: flex;
    column-gap: 5px;
  }

  .fault-phenomenon-option {
    display: flex;
    column-gap: 5px;
  }

  .user-options-wrapper {
    padding-right: 14px;

    .user-options {
      .user-option {
        height: 35px;
        display: flex;
        column-gap: 12px;
        cursor: pointer;
        padding: 8px 10px;
        box-sizing: border-box;

        &:hover {
          background-color: #f5f7fa;
        }

        .user-name {
          width: 200px;
        }

        .is-join-black-list,
        .user-phone {
          line-height: 19px;
        }
      }
    }
  }

  .order-create-form-wrapper {
    width: 100%;
    height: calc(100vh - 92px);
    box-sizing: border-box;
    padding: 12px;

    .order-create-form-container {
      display: flex;
      flex-direction: column;
      box-sizing: border-box;
      padding: 12px;
      background-color: #fff;
      height: 100%;
    }

    .header {
      width: 100%;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      background-color: #fff;
      align-items: center;
      padding: 0 12px;

      .title {
        font-size: 14px;
        color: #383838;
      }

      .btn_group {
        display: flex;
        gap: 5px;
      }
    }

    .divider {
      border-bottom: 1px dotted #d4d4d4;
      margin: 12px 0;
    }

    .form-container {
      flex: 1;
      height: 0;
      width: 100%;
      overflow: auto;
      display: flex;
      flex-direction: column;
      row-gap: 32px;

      .order {
        display: flex;
        flex-direction: column;
        background-color: #fff;
        padding: 0 12px;

        .title {
          font-size: 14px;
          padding-left: 6px;
          border-left: 3px solid $primaryColor;
          font-weight: bold;
        }

        :deep(.el-form) {
          display: flex;
          flex-wrap: wrap;
          column-gap: 100px;
          margin-top: 18px;
          row-gap: 18px;
          padding: 0 38px;

          .el-form-item {
            width: 440px;
            margin: 0;

            .el-form-item__label {
              height: 16px;
              line-height: 16px;
              margin: 0 0 3px 0;
            }

            .el-form-item__content {
              width: 100%;
              align-items: flex-start;

              .el-cascader,
              .el-input,
              .el-textarea,
              .el-select,
              .appointment-time {
                width: 382px !important;
              }

              .appointment-time {
                display: flex;
                column-gap: 4px;
              }

              .fault-desc-container {
                width: 100%;
                display: flex;
                flex-direction: column;
                row-gap: 8px;

                .quick-item-list {
                  display: flex;
                  flex-wrap: wrap;
                  column-gap: 8px;
                  row-gap: 4px;

                  .quick-item {
                    width: fit-content;
                    height: 24px;
                    border-radius: 24px;
                    border: 1px solid #eee;
                    padding: 0 8px;
                    line-height: 24px;
                    cursor: pointer;
                  }
                }
              }

              .el-select {
                max-width: unset;
                width: 100%;
              }

              .el-input {
                width: 100%;
                max-width: unset;
                height: 28px;

                .el-input__wrapper {
                  height: 26px;
                }
              }

              .el-form-item__error {
                margin: 0;
                padding-top: 4px;
              }

              .el-textarea {
                .el-textarea__inner {
                  width: 100% !important;
                  max-height: 200px !important;
                  min-height: 28px !important;
                  height: 28px;
                }
              }

              .desc-28-height {
                .el-textarea__inner {
                  max-height: 100px !important;
                  min-height: 28px !important;
                }
              }

              .desc-75-height {
                .el-textarea__inner {
                  max-height: 285px !important;
                  min-height: 75px !important;
                }
              }

              .upload_file_container {
                width: 100% !important;
                display: flex;
                flex-wrap: wrap;
                gap: 5px;

                .order-picture-upload {
                  width: 80px;
                  height: 50px;

                  .el-upload {
                    width: 100%;
                    height: 100%;

                    .el-upload-dragger {
                      display: flex;
                      align-items: center;
                      column-gap: 5px;
                      width: 100%;
                      height: 100%;
                      padding: 0;
                      background: none;
                      justify-content: center;
                    }
                  }
                }

                .file_list {
                  display: grid;
                  grid-template-columns: repeat(2, 1fr);
                  margin-top: 5px;
                  width: 100%;
                  row-gap: 5px;
                  column-gap: 12px;

                  .file_item {
                    flex: 1;
                    list-style: none;
                    display: flex;
                    column-gap: 5px;
                    height: 16px;
                    align-items: center;

                    .file_name {
                      width: 100%;
                      line-height: 14px;
                      text-overflow: ellipsis;
                      white-space: nowrap;
                      overflow: hidden;
                      text-align: center;
                      margin-top: 2px;
                    }
                  }
                }
              }
            }
          }
        }
      }

      .address {
        background-color: #fff;
        display: flex;
        flex-direction: column;
        padding: 0 12px;

        .title {
          font-size: 14px;
          padding-left: 6px;
          border-left: 3px solid $primaryColor;
          font-weight: bold;
        }
      }

      .custom_info {
        background-color: #fff;
        display: flex;
        flex-direction: column;
        padding: 0 12px;

        .title {
          font-size: 14px;
          padding-left: 6px;
          border-left: 3px solid $primaryColor;
          font-weight: bold;
        }

        .form-content {
          display: grid;
          grid-template-columns: repeat(2, 440px);
          column-gap: 100px;
          margin-top: 18px;
          row-gap: 18px;
          padding: 0 38px;

          :deep(.el-form) {
            .el-form-item {
              width: 100%;
              margin: 0;

              .el-form-item__label {
                height: 16px;
                line-height: 16px;
                margin: 0 0 3px 0;
              }

              .el-form-item__content {
                .el-form-item__error {
                  margin: 3px 0 0 0;
                  padding: 0;
                }

                .el-rate {
                  height: 28px;
                }

                .el-select {
                  width: 100% !important;
                }

                .el-date-editor {
                  height: 28px;
                  width: 100%;

                  .el-input__wrapper {
                    height: 26px;
                  }
                }

                .custom-field-upload {
                  display: flex;
                  gap: 5px;
                  flex-wrap: wrap;

                  .upload-wrapper {
                    width: 80px;
                    height: 50px;

                    .el-upload {
                      width: 100%;
                      height: 100%;
                      display: flex;
                      justify-content: center;
                      padding: 0;
                      box-shadow: 0 0 0 1px #dcdfe6 inset;
                      box-sizing: border-box;

                      .text {
                        line-height: 16px;
                        height: 16px;
                        color: #999;
                      }
                    }
                  }
                }

                .el-textarea {
                  height: 100%;
                  width: 100%;

                  .el-textarea__inner {
                    width: 100% !important;
                    min-height: 75px !important;
                    max-height: 140px !important;
                  }
                }
              }
            }
          }
        }
      }

      .customer {
        background-color: #fff;
        box-sizing: border-box;
        padding: 0 12px;

        .title {
          font-size: 14px;
          padding-left: 6px;
          border-left: 3px solid $primaryColor;
          font-weight: bold;
        }

        .form-box {
          display: flex;
          flex-wrap: wrap;
          margin-top: 18px;
          row-gap: 18px;
          padding: 0 38px;
          column-gap: 100px;

          :deep(.el-form-item) {
            width: 440px;
            margin: 0 !important;

            .el-form-item__label {
              height: 16px;
              line-height: 16px;
              margin: 0 0 3px 0;
            }

            .el-form-item__content {
              width: 100% !important;
              flex-direction: column;
              align-items: flex-start;

              .el-cascader,
              .el-input,
              .el-textarea {
                width: 382px !important;
              }

              .el-select {
                width: 382px !important;
                max-width: unset !important;
              }

              .detail_address {
                .el-textarea__inner {
                  width: 100% !important;
                  height: 28px;
                  min-height: 28px !important;
                  max-height: 155px !important;
                }
              }

              .address_identify {
                display: flex;
                gap: 12px;
                align-items: center;
                width: 382px;

                .el-textarea {
                  .el-textarea__inner {
                    width: 382px !important;
                    min-height: 95px !important;
                    max-height: 210px !important;
                  }
                }
              }

              .el-form-item__error {
                margin: 0;
                padding-top: 4px;
              }
            }
          }
        }
      }

      // .good-info {
      // flex: 1;
      // }
    }

    // 公司信息
    .customer_info_form_content {
      background-color: #fff;
      box-sizing: border-box;
      padding: 12px;
      margin-top: 12px;

      :deep(.el-form-item) {
        margin-bottom: 15px;
      }

      .title {
        font-size: 14px;
        border-left: 3px solid $primaryColor;
        color: #383838;
        padding-left: 6px;
      }

      .userinfo {
        display: flex;
        gap: 60px;

        .address_identify {
          .address_identify_content {
            display: flex;
            gap: 10px;

            .textarea {
              width: 300px;
            }

            .btn {
              padding: 0 10px;
              border-color: rgba($primaryColor, 0.8);
              color: rgba($primaryColor, 0.8);
              // border-radius: 4px;

              &:hover {
                border-color: $primaryColor;
                color: #fff;
                background-color: $primaryColor;
              }
            }
          }
        }

        .customer_name,
        .customer_phone {
          width: 240px;
        }

        .detail_address,
        .customer_address {
          width: 100%;
        }

        :deep(.el-form-item__content) {
          max-width: 700px;
        }
      }
    }
  }

  .pic {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    // margin-left: 4px;
  }

  :deep(.el-form-item--default) {
    --font-size: 12px;
  }

  .app-container {
    padding: 0 12px;
    padding-top: 10px;
  }

  .mar_r {
    margin-top: 10px;
    margin-right: 20px;
  }

  :deep(.el-form-item) {
    margin-bottom: 16px;
  }

  :deep(.el-main) {
    --el-main-padding: 0;
  }

  :deep(.code-dialog) {
    height: 100%;

    .el-dialog__body {
      padding: 0;
    }

    .header {
      display: flex;
      justify-content: flex-end;

      .w120 {
        width: 120px;
        margin-right: 5px;
      }

      .el-date-editor {
        width: 250px;
        margin-right: 10px;
      }

      .input-with-select {
        width: 180px;
        margin-right: 8px;
      }

      .mr_5 {
        margin-right: 5px;
      }

      .el-button + .el-button {
        margin-left: 8px;
      }

      .input-with-select_w {
        width: 250px;
        margin-left: 8px;
      }

      .w100 {
        width: 100px;
      }
    }

    .el-dialog__footer {
      border-top: 1px solid #e4e7ed;
      padding: 10px 20px;
    }

    .table-reg {
      width: 100%;
      margin: 10px 0;
      height: 486px;
    }

    .footer {
      padding: 10px 0;
      position: absolute;
      margin-bottom: 0;
      bottom: 0;
      z-index: 999;
    }
  }

  :deep(.demo-tabs) {
    .el-table {
      .cell {
        // text-align: center;
        font-size: 12px;
      }

      th.el-table__cell + th.el-table__cell {
        .cell {
          border-left: 1px solid #e7e3e3;
        }
      }
    }

    .el-table--border .el-table__cell {
      border-right: none;
    }

    .el-tabs__header {
      margin: 0;
    }

    .el-tabs__item {
      margin: 0 20px;
    }

    .el-tabs__nav-wrap::after {
      height: 1px;
    }

    .el-tabs__nav .el-tabs__active-bar {
      padding: 0 10px;
      position: absolute;
      bottom: 0;
      left: -10px;
    }

    .main_left {
      border: 1px solid #e4e7ed;
      border-bottom: none;
      border-radius: 2px;
      position: relative;
      height: calc(100% - 1px);

      .titile_h4 {
        border-bottom: 1px solid #e4e7ed;
        height: 40px;
        line-height: 40px;
        padding: 0 20px;
      }

      .ul_pop_up {
        padding: 0 30px 30px;

        .li_pop_up {
          padding: 5px 0;
          cursor: pointer;
          font-size: 12px;

          &:hover {
            color: #999;
          }
        }
      }

      .page_pages {
        width: 100%;
        overflow-x: auto;
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        bottom: 0;
      }

      .btn_save {
        width: 50px;
        height: 30px;
        border-radius: 2px;
      }

      .btn_cancel {
        width: 50px;
        height: 30px;
        border-radius: 2px;

        &:hover {
          border: 1px solid #e5e5e5;
          color: #999;
          background-color: #e5e5e5;
        }
      }
    }

    .main_right {
      padding: 12px 20px;
      height: calc(100% - 24px);
    }

    .table-user {
      margin: 10px 20px;
      height: 500px;
    }
  }

  .userinfo_select_empty {
    display: flex;
    justify-content: center;
  }

  .create-user-btn {
    width: -webkit-fill-available !important;
  }
</style>

<style lang="scss">
  .el-popover.monitor-yt-popover {
    padding: 6px 0;

    .user_item {
      font-size: 12px;
      margin: 0 12px;
      padding: 8px 12px;
      cursor: pointer;
      display: flex;
      align-items: center;
      flex-wrap: nowrap;

      &:hover {
        background-color: rgb(245, 247, 250);
      }
    }
  }
</style>
